Question

for my current project I would like to read values of a JSON file in JavaScript. As I am new to both of them I'm kinda lost. With the code below I get the following error in my JavaScript console:

XMLHttpRequest cannot load file:///Users/Fabio/Desktop/SkriptET/files.json. Received an invalid response. Origin 'null' is therefore not allowed access.

The file is saved there though.

index.html

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script type="text/javascript" src="javascript.js"></script>
  </head>
  <body>
  </body>
</html>

files.json

{
   "category":
    {
       "Gleichstromkreise":
        [
            {
                "title":"Elektrische Ladung Q",
                "url":"/elladq.html",
                "url_next": "/coulomb.html",
                "url_prev": "/index.html"    
            },
            {
                "title":"Coulombsches Gesetz",
                "url":"/coulomb.html",
                "url_next":"/el_spannung.html",
                "url_prev":"ellektrische_ladung_q.html"
            }
            ],
        "Elektrische Felder":
            [
                ...
            ]
    }
}

javascript.js

$.getJSON( "files.json", function( data ) {
    alert(data.category.Gleichstromkreise[0].title);
});
Was it helpful?

Solution

The problem isn't JSON, it's the Same Origin Policy. When your page is loaded from a local file rather than over HTTP, that's origin "null". Some browsers prevent ajax calls between origin null and origin null, even preventing loading files from the same directory.

If you ran that via a web server (you can install one locally for development), the files would have the same origin and the browser would allow you to load the JSON file.

OTHER TIPS

You cannot use AJAX on your local machine (the file: scheme). Your page must be uploaded to a server, or you must install a server on your machine and access http://localhost/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top