Javascript:无法从本地主机加载 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18559107/
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
Javascript: can't load JSON file from localhost
提问by Kappie001
I'm currently working through the book "Head first HTML5 programming". I want to load the content of a file named sales.json
from a web server on my own machine. I used wampserver for this.
我目前正在阅读“Head first HTML5 programming”这本书。我想加载sales.json
从我自己机器上的 Web 服务器命名的文件的内容。我为此使用了 wampserver。
In the folder wamp/www/gumball/
I put all relevant .html
, .js
and .css
files, and also the sales.json
file.
在文件夹中,wamp/www/gumball/
我放置了所有相关的.html
,.js
和.css
文件,以及sales.json
文件。
My JavaScript code is very simple:
我的 JavaScript 代码非常简单:
window.onload = function() {
var url = "http://localhost/gumball/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function() {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
This doesn't do anything! Typing the link: http://localhost/gumball/sales.json
in my browser opens the right file, so the link should be correct. Even when using the .js
files that come with the book (with a finished version of the application I'm trying to make), nothing loads.
这没有任何作用!输入链接:http://localhost/gumball/sales.json
在我的浏览器中打开正确的文件,所以链接应该是正确的。即使使用.js
本书附带的文件(使用我正在尝试制作的应用程序的完成版本),也没有加载任何内容。
Testing with alert statements tells me the request.onload
event never happens. I'm clueless as to why this is the case.
使用警报语句进行测试告诉我该request.onload
事件从未发生。我不知道为什么会这样。
A fact I don't quite understand yet: when I type: http://localhost/gumball/sales.json:
in my browser (I added a colon at the end of the link), I get a 403 Forbidden error! Why does this happen? Does this have something to do with my problem?
一个我还不太明白的事实:当我http://localhost/gumball/sales.json:
在浏览器中输入:时(我在链接末尾添加了一个冒号),我收到了 403 Forbidden 错误!为什么会发生这种情况?这与我的问题有关吗?
回答by Denys Séguret
I open html document with firefox
我用firefox打开html文档
Your HTML document must be open with a URL in http://
, not file://
, if you want it to be able to open in javascript another document, unless the second document is served with relevant CORS headers.
您的HTML文件必须与一个URL打开http://
,不file://
,如果你希望它能够在JavaScript中打开另一个文件,除非第二份文件送达相关CORS标头。
This is due to same origin policy.
这是由于同源策略。
As you have a local WAMP server, there is no problem : simply open your file using a http://
URL like you do for your JSON file.
由于您拥有本地 WAMP 服务器,因此没有问题:只需使用http://
URL打开您的文件,就像您对 JSON 文件所做的那样。