开发者

XMLHttpRequest cannot load file://... Origin null is not allowed by Access-Control-Allow-Origin [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 9 years ago.

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

<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,

{ 
  "firstName": "John",
  "lastName": "Doe",
  "age": 25
}

When I open the getjson.html file in the browser, it gives an error:

开发者_运维知识库

"XMLHttpRequest cannot load file://..... Origin null is not allowed by Access-Control-Allow-Origin."

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.


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.


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 !

I have put this header on my remote php script:

header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);

and it seems to work ! More explanation here: Rannpháirtí anaithnid/CORS

It may work on a "phone gap" application instead of using jquery and jsonp?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜