jquery - 显示 JSON 数据

标签 jquery json

我真的有点困惑:

我在名为 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/

相关文章:

jquery - 使用 data() 分配的 jquery 数据可以保存多久?

jquery克隆表单元素并将其插入表单中

android - 获取库播放列表艺术品 Apple Music API

javascript - 将数组添加到对象

java - 从表中访问数据 - JSON/Java

javascript - json JSON 中出现意外标记 o

javascript - 无法专注于 Bootstrap Carousel 中的输入字段

jquery - if 语句选择器的差异

jquery - 如何突出显示 highstock 中的某个范围?

javascript - 如何将层次结构数据数组转换为 D3-Tree-Region 的正确 JSON 格式