getJson()在chrome中不起作用 [英] getJson() is not working in chrome
问题描述
getJson j-query方法在其他所有浏览器中都无法使用chrome。
以下是我的代码
$(document).ready(function(){
$ b $ .getJSON('aptitude14.json',function(data){
///我的代码在这里
};
$;
错误我得到chrome是
我的JSON文件位于同一个文件夹中
$您正在尝试使用 file:
协议从您的客户端计算机读取文件,该文件位于: <你可以做什么只是简单地禁用chrome中的web安全性,如果它只是一个样本测试,打开你的Chrome与这个参数的命令行一致:
--disable-web-security
如果它不是样本测试,你必须把你的文件在您有权访问的服务器上,使用http ajax调用而不是文件ajax调用。
如果您在网络上遇到此问题,将会有两个选项修复它,使用JSONP或启用CORS。但在文件协议中,我可以为您提供假的JSONP调用,如下所示:
-first it you json file is like this:
[{
name:abc// ...
},
{
name:efg // ...
}]
将其更改为(将其包装在函数中($ {
name:abc// ...
}):
callback ,
{
name:efg// ...
}])
然后做这个而不是jQuery ajax调用:
window.callback = function(jsonObj){
//
};
var script = document.createElement('script');
//因为这是一个假的jsonp调用,您不需要添加?callback =回调到url
script.src ='aptitude14.json';
document.getElementsByTagName('head')[0] .appendChild(script);
getJson j-query method is not working in chrome while it is working in all other browsers
following is my code
$(document).ready(function(){
$.getJSON('aptitude14.json',function(data){
/// my code goes here
}; };
error i am getting in chrome is
my JSON file is with in the same folder
You are trying to read a file from your client machine with file:
protocol, which is not safe. It doesn't work in Chrome, because Chrome cares about the security issues more than other browsers. it seems to me you are trying to create a sample ajax.
What you can do is simply disable the web security in chrome, if it is just a sample testing, open your Chrome in comand line with this parameter: --disable-web-security
and if it is not a sample test, you have to put your file on a server that you have access to it and use http ajax call instead of file ajax call.
If you had this problem on the web, there would be two options to fix it, using JSONP or enabling CORS. but in file protocol I can offer you to fake a JSONP call like this:
-first it you json file is like this:
[{
name : "abc" //...
},
{
name : "efg" //...
}]
change it to (wrap it in a function call):
callback([{
name : "abc" //...
},
{
name : "efg" //...
}])
then do this instead of jQuery ajax call:
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);
这篇关于getJson()在chrome中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!