我需要循环下面的json但是下面的代码循环遍历我的json中的每个字符并显示" undefined" :(以下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);
});
})
答案 0 :(得分:2)
看起来,您的NewsObject
不是JSON
对象,而是字符串。这可能是因为JQuery无法猜测响应类型,因此您可能需要为dataType
请求(documentation)指定$.post
:
$.post("server/news.php", null, function(e){ ... }, 'json');
P.S。此外,JSON
看起来有效,我希望看到类似{'a':'b'}
的内容,但您有{'a':'b'} {'c':'d'}
。
已更新。根据以下评论,我建议您为server/news.php
使用下一个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错误。