javascript XMLHttpRequest 无法加载文件://... Access-Control-Allow-Origin 不允许 Origin null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6479694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XMLHttpRequest cannot load file://... Origin null is not allowed by Access-Control-Allow-Origin
提问by chinmay
I see that the above question was asked earlier, however even after referring them I wasn't able to figure out a way for me, hence I took the liberty to start a new post for this question.
我看到上面的问题是早些时候被问到的,但是即使在参考他们之后我也无法为我找到方法,因此我冒昧地为这个问题开始了一个新帖子。
I have a getjson.html file containing the following code
我有一个包含以下代码的 getjson.html 文件
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.getJSON("json_data.txt",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
The json_data.txt contains the following,
json_data.txt 包含以下内容,
{
"firstName": "John",
"lastName": "Doe",
"age": 25
}
When I open the getjson.html file in the browser, it gives an error:
当我在浏览器中打开 getjson.html 文件时,它给出了一个错误:
"XMLHttpRequest cannot load file://..... Origin null is not allowed by Access-Control-Allow-Origin."
“XMLHttpRequest 无法加载 file://..... Access-Control-Allow-Origin 不允许 Origin null。”
Someone Please suggest a simple solution regarding this about how could I make this thing possible.
有人请提出一个关于我如何使这件事成为可能的简单解决方案。
P.S: I am writing a web app on go.
PS:我正在编写一个网络应用程序。
回答by Troy SK
Are you directly opening an HTML file? The file needs to be placed on a web server then executed. Normally browsers don't allow file:///
protocol for AJAX calls for security reasons.
你是直接打开一个 HTML 文件吗?该文件需要放置在 Web 服务器上然后执行。通常file:///
,出于安全原因,浏览器不允许AJAX 调用协议。
回答by user2291712
I am reading your problem a bit late (spring 2013) and think I have found a solution to the limitation of CORS XHR cross domain in a file:// context !
我读你的问题有点晚(2013 年春季),并认为我已经找到了解决 file:// 上下文中 CORS XHR 跨域限制的解决方案!
I have put this header on my remote php script:
我已将此标头放在我的远程 php 脚本上:
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
and it seems to work ! More explanation here: Rannpháirtí anaithnid/CORS
它似乎有效!这里有更多解释:Rannpháirtí anaithnid/CORS
It may work on a "phone gap" application instead of using jquery and jsonp?
它可能适用于“电话间隙”应用程序而不是使用 jquery 和 jsonp?