我真的有点困惑:
我在名为 data.json 的文件中有以下 JSON 数据
{
"locations": [
{
"title": "The Space Needle",
"latitude": 47.619,
"longitude": -122.348
},
{
"title": "Albany",
"latitude": 46,
"longitude": -74
}
]
}
当我使用以下代码尝试显示数据时,我什么也没得到:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Another gone south</title>
<script src="http://code.jquery.com/jquery-1.8.0.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function(){
$.getJSON("data.json",function(data){
$.each(data.locations, function(i,location){
content += '<p>' + location.title + '</p>';
content += '<p>' + location.latitude + '</p>';
content += '<p' + location.longitude + '</p>';
content += '<br/>';
alert('aler called');
$(content).appendTo("#loc");
});
});
});
/* ]]> */
</script>
</head>
<body>
<div class="container">
<div class="span-24">
<h2>Check out the following locations:</h2>
<div id="loc">
</div>
</div>
</div>
</body>
</html>
最佳答案
假设返回了你的 json,你的循环似乎很好 你可能需要做的唯一一件事是在使用它之前解析你的 JSON 结果:
在JayC
所说之后,我再次查看了这个,我将 JSON 值添加到我的示例中的一个字符串中(d'oh),当然,我将它作为一个对象,每个都工作得很好很好。
参见DEMO使用 JSON 对象(不是字符串)
基本上,您的代码应该工作得很好,这意味着请求要么生成错误,要么您什么也没有返回。
检查浏览器中的调试控制台是否有错误。在 FF 中您可以使用 FireBug,或者在 Chrome 和 IE 中使用内置的 FireBug。
关于jquery - 显示 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11956865/