Javascript:无法从localhost加载JSON文件 [英] Javascript: can't load JSON file from localhost

查看:140
本文介绍了Javascript:无法从localhost加载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 文件,以及销售额.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.

使用alert语句进行测试告诉我,$ code> 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:/ /lhosthost/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.

这篇关于Javascript:无法从localhost加载JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆