Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load local JSON files in Javascript

Tags:

I'm writing a web app (well, actually it will eventually be an OS X Dashboard widget, but I decided to prototype it first as a simple web page) that needs to load some initializing data from a local JSON file. My code looks like this:

function loadDatos() {   
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'datos.json', true);
    xobj.onReadyStateChange = function () {
        if (xobj.readyState == 4) {
            var jsonTexto = xobj.responseText;
            ProcessTheData(jsonTexto);
        }
    }
    xobj.send(null);
}

The function get called from an onLoad() event in the HTML file's BODY tag. Now, from what I see when debugging, the function gets executed, but the onReadytStateChange event handler never gets called.

What should I do? I thought it was a bit odd to use a XMLHttpRequest to access a local file, but the new tutorials I've seen that deal with this issue seem to say that it should work (the 99% of docs I've seen talk about how to load JSON from a remote server, not from a local file).

I'm testing using Firefox 3.6.10, but I've also tried with Safari 4.

like image 834
PaulJ Avatar asked Oct 09 '10 15:10

PaulJ


People also ask

Can we import JSON file in JavaScript?

We can read this JSON data in JavaScript using the import statement this way: <! ---./index. js--> import data from './data.

How do I read a local file in JSON?

Chrome allows you to access local JSON or other data files if you launch it with the --allow-file-access-from-files flag. I checked this with the code above on version 34.0. 1847.131 m; it should work on other versions as well.

How do I install a local JSON file?

You can simply use the $. getJSON() method to load local JSON file from the server using a GET HTTP request. If the JSON file contains a syntax error, the request will usually fail silently.


2 Answers

onreadystatechange property has no capital letters. See: MDC XMLHttpRequest

like image 154
25 revs, 4 users 83% Avatar answered Sep 25 '22 17:09

25 revs, 4 users 83%


Unless we add extension .json and MIMETYPE application\json, IIS will throw an error.

See here: http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/cd72c0dc-c5b8-42e4-96c2-b3c656f99ead.mspx?mfr=true

like image 39
aharisankar Avatar answered Sep 25 '22 17:09

aharisankar