2012-12-14 47 views
1

我的问题很简单,我有一个名为new.json的文件,我试图使用JQuery来加载和显示数据。我一直在写JavaScript代码:

$.getJSON("new.json", function(data){ 
     // I have placed alert here previously and realized it doesn't go into here 
     $.each(data.streetCity, function(i,s){ 
      alert(s); 
     }); 
    }); 
} 

和new.json数据看起来如下:

{"streetCity": 
    { 
     "1":"Abergement-Clemenciat", 
     "2":"Abergement-de-Varey", 
     "3":"Amareins" 
    } 
}; 
+0

确保'new.json'与运行生成ajax请求的JS的文件位于同一目录中。我很肯定你也不想要'''。 –

+0

如果没有在本地机器上运行服务器,某些浏览器将不会允许Ajax无需调整设置 – charlietfl

+0

如果您使用Chrome,可能会出现重复问题:http://stackoverflow.com/questions/2541949/problems-with-jquery-getjson-使用本地文件在chrome – apsillers

回答

11

如果您使用的是Chrome。由于Chrome不允许xmlhttprequest请求本地文件。因此jQuery的不能加载您new.json

您可以添加

--allow-文件访问从档案

Chrome浏览器的启动命令。这可以允许的XMLHttpRequest如果您正在使用jQuery来加载本地资源

+1

我正在做另一个应用程序,并提醒我这个问题。我已经尝试过,是的,现在正在工作,谢谢。 – yi2ng2

2

1.5+你可以链中的错误处理程序上调用,看看是怎么回事:

$.getJSON("new.json", function(data){ 
     // I have placed alert here previously and realized it doesn't go into here 
     $.each(data.streetCity, function(i,s){ 
      alert(s); 
     }); 
    }).error(function(jqXhr, textStatus, error) { 
       alert("ERROR: " + textStatus + ", " + error); 
    }); 

new.json可能是不同的路径比调用页面。另外,如果您的代码片段准确无误,则不需要脚本中的最后一个大括号或json中的最后一个分号。

1

你的问题是';' (分号)在JSON文件中。 JSON响应不需要分号。删除你的例子应该工作正常!