4

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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
chinmay
  • 1,373
  • 5
  • 15
  • 15

2 Answers2

7

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.

rootmeanclaire
  • 808
  • 3
  • 13
  • 37
Troy SK
  • 1,279
  • 7
  • 14
0

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?

NullUserException
  • 83,810
  • 28
  • 209
  • 234