1

So I know this is so lame to ask this question as I have spent a day searching on this subject without any success. As many others, I'm facing the crossdomain problem. The suggestion I see everywhere is to update the JSON file on a server or use localhost which I can't use because my assignment is not allowed to do so.

I am posting this question hoping there is some other solution for this. I need to fetch data from a JSON file locally using pure JavasSript and Ajax which does not involve hosting on a server nor localhost (using absolute path is also a bad idea).

This is my code so far:

function loadJSON(callback) {
  var xobj = new XMLHttpRequest();
      xobj.overrideMimeType("application/json");
      xobj.open('GET', '/json/userinfo.json', true);
      xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
          callback(xobj.responseText);
        }
  };
  xobj.send(null);
}

(function() {
  loadJSON(function(response){
    var actual_JSON = JSON.parse(response);
    console.log(actual_JSON);
  })
})()
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Lucky Lam
  • 125
  • 2
  • 14
  • Which browser used ? , chrome ? See http://stackoverflow.com/questions/32996001/jquery-load-only-working-in-firefox – guest271314 Dec 05 '15 at 17:44
  • If it's IE then you must force `ActiveXObject('Microsoft.XMLHTTP')` for local files: http://stackoverflow.com/questions/2142156/read-file-urls-in-ie-xmlhttprequest – GitaarLAB Dec 05 '15 at 17:49
  • @guest271314 I can't do anything with the browsers because my trainer will have it run on his own PC – Lucky Lam Dec 06 '15 at 04:29
  • @LuckyLam Is `js` at post not returning expected results ? – guest271314 Dec 06 '15 at 04:31
  • @guest271314 Yes it gives error on Chrome saying "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource." On Firefox I can get it work BUT having to be with absolute path, relative path is not working, giving error "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied" – Lucky Lam Dec 06 '15 at 05:26
  • @LuckyLam Simplest method to return expected results at chrome would be to launch chrome with `--allow-file-access-from-files` flag set – guest271314 Dec 06 '15 at 05:39

1 Answers1

0

You won't be able to access local files using AJAX/XHR. Its not designed for this purpose. What you can do is assign your json data into a variable in the json file,

var data = [{

}];

and then load your json file using script tag like below:

<script type="text/javascript" src="file_name.json"></script>

Now all the json data can be accessed using the data variable.

Kaashan
  • 352
  • 3
  • 12