[英]jQuery ajax request from local file (Origin 'null' not allowed access)
I am making a jQuery ajax call from a local file which retrieves JSON data from a webserver: 我正在从本地文件进行jQuery ajax调用,该文件从Web服务器检索JSON数据:
$.ajax({
type: 'GET',
url: 'http://mywebsite.com/data.json',
dataType: 'json',
success: showData
});
and I am getting the following error on chrome: 我在chrome上收到以下错误:
XMLHttpRequest cannot load http://mywebsite.com/data.json. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
I have read through a lot of other answers which seem to come to the conclusion that you cannot make ajax requests from local files with chrome, so the solutions are: 我已经阅读了许多其他答案,这些答案似乎可以得出结论,即您无法使用chrome从本地文件发出ajax请求,因此解决方案是:
but neither of these options are suitable for me. 但是这些选项都不适合我。
However, when I host the JSON data on another site (myjson.com), so that the line in the ajax request reads 但是,当我将JSON数据托管在另一个站点(myjson.com)上时,ajax请求中的行将读取
url: 'https://api.myjson.com/bins/myfile'
the file loads perfectly and the data is correctly displayed. 文件加载完美,数据正确显示。
Why is the ajax request allowed to 'myjson.com' but not to 'mywebsite.com'? 为什么允许对“ myjson.com”而不是“ mywebsite.com”使用ajax请求?
Edit: 编辑:
I have the line 我有线
Header set Access-Control-Allow-Origin "*"
in my apache2.conf file 在我的apache2.conf文件中
What you need to do is create a .htaccess
file in your document root and add the following lines to it: 您需要做的是在文档根目录中创建一个
.htaccess
文件,并在其中添加以下几行:
<FilesMatch "\.(json)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
What the above lines do is, they allow Cross origin resource sharing for all domains on .json files thus removing the error. 上面几行所做的是,它们允许.json文件上所有域的跨域资源共享,从而消除了错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.