开发者

How to load local JSON files in Javascript

开发者 https://www.devze.com 2023-01-19 20:42 出处:网络
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

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;开发者_如何学C
            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.


onreadystatechange property has no capital letters. See: MDC XMLHttpRequest


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号