Javascript:无法从本地主机加载 JSON 文件
我目前正在阅读Head first HTML5 programming"一书.我想从我自己机器上的 Web 服务器加载名为 sales.json
的文件的内容.我为此使用了 wampserver.
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.
在文件夹 wamp/www/gumball/
我把所有相关的 .html
、.js
和 .css
文件,以及 sales.json
文件.
In the folder wamp/www/gumball/
I put all relevant .html
, .js
and .css
files, and also the sales.json
file.
我的 JavaScript 代码很简单:
My JavaScript code is very simple:
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;
}
这没有任何作用!在我的浏览器中键入链接: http://localhost/gumball/sales.json
会打开正确的文件,因此链接应该是正确的.即使使用本书附带的 .js
文件(以及我正在尝试制作的应用程序的完成版本),也没有加载任何内容.
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.
使用警报语句进行测试告诉我 request.onload
事件永远不会发生.我不知道为什么会这样.
Testing with alert statements tells me the request.onload
event never happens. I'm clueless as to why this is the case.
一个我还不太明白的事实:当我在浏览器中输入:http://localhost/gumball/sales.json:
时(我在链接末尾添加了一个冒号),我得到一个 403 Forbidden 错误!为什么会这样?这跟我的问题有关系吗?
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?
推荐答案
我用firefox打开html文档
I open html document with firefox
您的 HTML 文档必须使用 http://
中的 URL 打开,而不是 file://
,如果您希望它能够在 javascript 中打开另一个文档,除非第二个文档带有相关的 CORS 标头.
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.
这是由于同源政策.
由于您有本地 WAMP 服务器,所以没有问题:只需使用 http://
URL 打开您的文件,就像您打开 JSON 文件一样.
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.
相关文章