我尝试用jQuery在html文件中显示JSON数据。
但是在html中我甚至没有输出 null
或 unindefied
我尝试使用Flickr的外部JSON数据,至少看到[Object]
此外,我尝试在本地服务器上测试这两个文件 - HTML和JSON - 再没有
我在我的服务器上为application / json添加MIME类型
我查了JSON-它是有效的
在Firebug中,我看到了JSON响应(见下图)
在同一页面上,如果重要的话,我会使用jQuery mobile和DW Fluid网格布局。
我的JSON是使用PHP json_encode:
生成的({ "title": "Art and Culture",
"items": [
{"id":"kunst-im-tunnel","lat":"51.219917"},
{"id":"kunsthalle","lat":"51.227568"},
{"id":"kunstsammlung-nordrhein-westfalen","lat":"51.22841"}]
})
JSON的PHP代码
<?php
header('Cache-Control: no-store, no-cache, must-revalidate, private, post-check=0, pre-check=0');
header('Pragma: no-cache');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json; charset=utf-8');
$out = json_encode($post);
echo "({ \"title\": \"Art and Culture\",\"items\": " .$out." })";
?>
我的javascript代码是:
$.getJSON("http://example.com/app.php?cat=category&jsoncallback=?",
{format: "json"},
function(data){
$.each(data.items, function(i,item){
$('<li>' + item.id + '</li>').appendTo("#list");
});
});
Firebug的屏幕截图:
答案 0 :(得分:1)
({ "title": "Art and Culture",
"items": [
{"id":"kunst-im-tunnel","lat":"51.219917"},
{"id":"kunsthalle","lat":"51.227568"},
{"id":"kunstsammlung-nordrhein-westfalen","lat":"51.22841"}]
})
IS NOT VALID JSON。
但是这个是有效的JSON
{ "title": "Art and Culture",
"items": [
{"id":"kunst-im-tunnel","lat":"51.219917"},
{"id":"kunsthalle","lat":"51.227568"},
{"id":"kunstsammlung-nordrhein-westfalen","lat":"51.22841"}]
}
它会很好地工作。以下是工作示例http://jsfiddle.net/cqfQp/1/
使用jsonlint验证JSON。
另一个建议是,尽量避免在循环中调用append
函数。创建一个变量并仅调用该函数一次。像这样的东西
var strItems="";
$.each(data.items, function(i,item){
strItems+='<li>' + item.id + '</li>';
});
$("#list").html(strItems);
编辑:确保在文档ready上调用getJSON函数
$(function(){
$.getJSON("http://example.com/app.php?cat=category&jsoncallback=?",function(data){
var strItems="";
$.each(data.items, function(i,item){
strItems+='<li>' + item.id + '</li>';
});
$("#list").html(strItems);
});
});
答案 1 :(得分:0)
您正在生成无效的JSON - 包含整个JSON表达式的括号不应该在那里。