-1

I am new to this, it may be an easy question. I have explored enough about this on internet. I just need some more insight in this issue : I am using this to get a json file which is one hierarchy down from where index.html is present in my directory structure. I am using jquery.ajax as below:

$.ajax({
  url: "../myFile.json",
  dataType: 'json',
  success: function(result, Status, jqXHR) { 
    MyFunction(result);
  },
  error: function(Status) {
    alert(Status.statusText + ": Wrong input. Please check the file.");
  }
});

Here, I am trying to access myFile.json as shown below. This doesn't work and I get error in firefox something like this

(Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource....)

When I keep myFIle.json in the same directory(or above the hierarchy of directory) where index.html is, it works absolutely fine.

NOTE: I am not hosting it anywhere. I have just made a simple index.html and running it in my machine in firefox.

Please throw some light on this issue. I want clear concept behind what is happening here.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Mazhar MIK
  • 1,022
  • 12
  • 14

1 Answers1

1

This is the Same Origin Policy. It's a security feature and you can read more details of how it is implemented in general in this answer.

Most browsers do not allow you to read files from the file system. This is an important security feature, imagine if you double-clicked an HTML attacked in an email. The browser would save it to a temporary folder, the browser would open it, and it could then read confidential data from other parts of your hard disk and send it to the attacker's website.

Firefox is slightly laxer. It allows you to read files so long as they are in the same directory (or a subdirectory of) the file the HTML document is in.

By moving the JSON to a level above that directory, you move it out of the area the browser trusts the JavaScript to access. Don't do that.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335