2

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.

In the folder wamp/www/gumball/ I put all relevant .html, .js and .css files, and also the sales.json file.

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;
}

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.

Testing with alert statements tells me the request.onload event never happens. I'm clueless as to why this is the case.

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?

4

1 回答 1

3

我用firefox打开html文档

您的 HTML 文档必须使用 中的 URL 打开http://,而不是file://如果您希望它能够在 javascript 中打开另一个文档,除非第二个文档带有相关的CORS 标头

这是由于同源政策

由于您有一个本地 WAMP 服务器,所以没有问题:只需使用http://URL 打开您的文件,就像您为 JSON 文件所做的那样。

于 2013-09-01T14:03:32.743 回答