0

我需要遍历下面的 json,但下面的代码循环遍历我的 json 中的每个字符并显示“未定义”:(下面的 json 有什么问题吗???感谢您的帮助)

{"news_id":"1","news_title":"News Title One","news_date":"2012-03-20","news_pic":"album-bb[6].jpg","news_desc":"Here goes the news title one Here goes the news title one Here goes the news title one Here goes the news title one.","gallid":"3"}
{"news_id":"2","news_title":"News Title Two","news_date":"2012-04-14","news_pic":"174863_163190093755777_2032987021_q.jpg","news_desc":"News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two.","gallid":"0"}

这是我在点击事件时触发的代码:

var phpNews;
var NewsObject;

$(document).ready(function () {

    $("#btnNewsPage").click(function()
    {
        $.post("server/news.php",null,function(e){
            NewsObject = e;
            $.mobile.changePage("#NewsPage");
        });
    });

    $('#NewsPage').live('pagebeforeshow',function(event, ui){
        var list;
        $.each(NewsObject, function(k,v){
            list = v.news_title;
        });

        $("#displayNews").html(list);
    });

})
4

1 回答 1

2

看起来,你NewsObject的不是JSON对象而是字符串。这可能会发生,因为 JQuery 无法猜测响应类型,因此您可能需要dataType为您的$.post请求指定(文档):

$.post("server/news.php", null, function(e){ ... }, 'json');

PS 另外,您JSON看起来无效,我希望看到类似的东西{'a':'b'},但您有{'a':'b'} {'c':'d'}

更新。根据下面的评论,我建议您使用下一个 PHP 代码server/news.php

<?php 

require "../includes/config.php"; 
require "../includes/h.conn.php"; 
require "../includes/admin.id.php"; 

$strSQL = "select * from news where admin_id=" .$admin_id; 
$objRS = mysql_query($strSQL);
$News_Obj = array();

while ($row = mysql_fetch_assoc($objRS)) {
    $record = array (
               "news_id" => $row['news_id'], 
               "news_title" => $row['news_title'], 
               "news_date" => $row['news_date']
    );
    $News_Obj[] = $record; 
}

// don't forget to clear after yourself: mysql_free_result, disconnect

header("Content-type: application/json");
echo json_encode($News_Obj);
?>

您还可以使用 Firebug 查看究竟返回了什么脚本以及在您发出请求时发生了哪些 HTTP 或 Javascript 错误。

于 2012-04-13T15:12:39.790 回答