来自本地文件系统的 jQuery Ajax 请求(Windows file:///)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5469440/
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
jQuery Ajax request from local filesystem (Windows file:///)
提问by Emmanuel
I'm trying to do an ajax request to get the contents of "http://localhost/"
running on Windows Wamp Server.
我正在尝试执行 ajax 请求以获取"http://localhost/"
在 Windows Wamp Server上运行的内容。
The script is running from something like this:
脚本从这样的东西运行:
file:///C:/my/path/index.html
file:///C:/my/path/index.html
I'm just using a standard $.ajax request to try and get the contents of localhost:
我只是使用标准的 $.ajax 请求来尝试获取 localhost 的内容:
$.ajax({
type: 'GET',
url: 'http://localhost/',
success: function(data) {
alert('success');
}, error: function (data) {
alert('failed');
}
});
I can't get it to be successful though... Seems to be some problem with the local filesystem or something. I'm not too sure.
虽然我无法让它成功......似乎是本地文件系统或其他问题。我不太确定。
回答by Emmanuel
Problem Solved!
问题解决了!
I just had to add this header to my index.php file for http://localhost/
我只需要将此标头添加到http://localhost/ 的index.php 文件中
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Origin: *');
Thanks for your help anyhow guys!
无论如何,感谢您的帮助!
回答by lonesomeday
You say that the script is running from a file:///
URL. It's best not to do AJAX requests from file
URLs, because they are treated inconsistently. Chrome, for example, entirely disallows them.
您说脚本是从file:///
URL运行的。最好不要从file
URL执行 AJAX 请求,因为它们被处理不一致。例如,Chrome 完全禁止它们。
However, your bigger problem here is the same-origin policy: you can only make AJAX requests to the same host as the web page itself. file:///
and http://localhost
are notthe same host (even if they are the same machine).
但是,这里更大的问题是同源策略:您只能向与网页本身相同的主机发出 AJAX 请求。 file:///
和http://localhost
是不是在同一台主机(即使它们是在同一台机器)。
It's best to run everything off http://localhost
.
最好把一切都跑掉http://localhost
。
回答by Rob Williams
This probably won't work, as the browser will think this is a cross-domain request. You've accessed the file via a file:// URL, but are trying to retrieve data from http://localhost. Try accessing your original file from http://localhostas well, and it'll probably start to work.
这可能不起作用,因为浏览器会认为这是一个跨域请求。您已经通过 file:// URL 访问了该文件,但正在尝试从http://localhost检索数据。尝试从http://localhost访问您的原始文件,它可能会开始工作。