如何在 Javascript 中加载本地 JSON 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3896270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:33:06  来源:igfitidea点击:

How to load local JSON files in Javascript

javascriptjsondashboard

提问by PaulJ

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:

我正在编写一个需要从本地 JSON 文件加载一些初始化数据的 Web 应用程序(好吧,实际上它最终将成为一个 OS X 仪表板小部件,但我决定首先将其原型化为一个简单的网页)。我的代码如下所示:

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.

该函数从 HTML 文件的 BODY 标记中的 onLoad() 事件调用。现在,从我在调试时看到的情况来看,该函数被执行,但 onReadytStateChange 事件处理程序永远不会被调用。

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).

我该怎么办?我认为使用 XMLHttpRequest 访问本地文件有点奇怪,但是我看到的处理这个问题的新教程似乎说它应该可以工作(我看到的 99% 的文档都在谈论如何从远程服务器加载 JSON,而不是从本地文件)。

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

我正在使用 Firefox 3.6.10 进行测试,但我也尝试过使用 Safari 4。

采纳答案by gblazex

onreadystatechangeproperty has no capital letters. See: MDC XMLHttpRequest

onreadystatechange属性没有大写字母。请参阅:MDC XMLHttpRequest

回答by aharisankar

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

除非我们添加扩展名.json和 MIMETYPE application\json,否则IIS 将抛出错误。

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

请参阅此处:http: //www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/cd72c0dc-c5b8-42e4-96c2-b3c656f99ead.mspx?mfr=true