【问题标题】:getJson() is not working in chromegetJson() 在 Chrome 中不起作用
【发布时间】:2014-02-02 06:37:48
【问题描述】:

getJson j-query 方法在 Chrome 中不起作用,而在所有其他浏览器中都可以使用

以下是我的代码

$(document).ready(function(){

$.getJSON('aptitude14.json',function(data){


     /// my code goes here

}; };

我在 chrome 中遇到的错误是

我的 JSON 文件在同一个文件夹中

【问题讨论】:

  • 您正在使用“同源”安全策略。 Chrome 对本地资源也非常严格(它们不被视为“同源”)。
  • 我必须做什么
  • 你必须不使用文件系统。安装网络服务器。
  • 哇它的工作 thq 为您的回答 Kevin B ,, sje397

标签: jquery json google-chrome


【解决方案1】:

您正尝试使用 file: 协议从客户端计算机读取文件,这是不安全的。它在 Chrome 中不起作用,因为 Chrome 比其他浏览器更关心安全问题。在我看来,您正在尝试创建一个示例 ajax。

你可以做的只是简单地禁用 chrome 中的 web 安全,如果它只是一个示例测试,请使用以下参数在命令行中打开你的 Chrome: --disable-web-security

如果不是示例测试,您必须将文件放在可以访问它的服务器上,并使用 http ajax 调用而不是文件 ajax 调用。

如果您在网络上遇到此问题,有两个选项可以解决它,使用 JSONP 或启用 CORS。但在文件协议中,我可以让您像这样伪造 JSONP 调用:

-首先你的json文件是这样的:

[{
   name : "abc" //...
},
{
   name : "efg" //...
}]

将其更改为(将其包装在函数调用中):

callback([{
   name : "abc" //...
},
{
   name : "efg" //...
}])

然后这样做而不是 jQuery ajax 调用:

window.callback = function(jsonObj){
    //
};
var script = document.createElement('script');
//since this is a fake jsonp call you don't need to add ?callback=callback to url
script.src = 'aptitude14.json';
document.getElementsByTagName('head')[0].appendChild(script);

【讨论】:

    猜你喜欢
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 2012-05-06
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多