[英]Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource
I am following a book example hence the code is very simple. 我正在关注一本书的例子,因此代码非常简单。
This is the code: 这是代码:
jQuery.get("ajax_search_results.php",
{ s:search_query },
write_results_to_page, "html");
And the code is ajax_search_results.php has: 代码是ajax_search_results.php:
<div id="ajax_search_results">
<ul>
<li><a href="#">First result</a></li>
<li><a href="#">Second result</a></li>
<li><a href="#">Third result</a></li>
<li><a href="#">More...</a></li>
</ul>
</div>
This works as expected in the Firefox. 这在Firefox中可以正常工作。 But in Chrome, I can see the error following message in the JS console: 但在Chrome中,我可以在JS控制台中看到错误消息:
XMLHttpRequest cannot load
file:///C:/xampp/xampp/htdocs/snk/ajax_search_results.php?s=keyword.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.
Can you please help identify the problem? 你能帮忙找出问题所在吗?
If your problem is like the following while using Google Chrome: 如果您在使用Google Chrome时遇到以下问题,请执行以下操作:
[XMLHttpRequest cannot load file. [XMLHttpRequest无法加载文件。 Received an invalid response. 收到无效回复。 Origin 'null' is therefore not allowed access.] 因此不允许原点'null'访问。]
Then create a batch file by following these steps: 然后按照以下步骤创建批处理文件:
Open notepad in Desktop. 在桌面中打开记事本 。
start "chrome" "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe" --allow-file-access-from-files exit 启动“chrome”“C:\\ Program Files(x86)\\ Google \\ Chrome \\ Application \\ chrome.exe” - allow-file-access-from-files退出
This will do what? 这会做什么? It will open Chrome.exe with file access. 它将打开具有文件访问权限的Chrome.exe。 Now, from any location in your computer, browse your html files with Google Chrome. 现在,从计算机的任何位置,使用Google Chrome浏览您的html文件。 I hope this will solve the XMLHttpRequest problem. 我希望这将解决XMLHttpRequest问题。
Keep in mind : Just use the shortcut bat file to open Chrome when you require it. 请注意:只需使用快捷方式bat文件即可在需要时打开Chrome。 Tell me if it solves your problem. 告诉我它是否解决了你的问题。 I had a similar problem and I solved it in this way. 我有类似的问题,我以这种方式解决了它。 Thanks. 谢谢。
add this at the top of file, 将其添加到文件顶部,
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
This is supposedly because you trying to make cross-domain request, or something that is clarified as it. 这可能是因为您尝试进行跨域请求,或者是为此澄清的内容。 You could try adding header('Access-Control-Allow-Origin: *');
您可以尝试添加header('Access-Control-Allow-Origin: *');
to the requested file. 到请求的文件。
Also, such problem is sometimes occurs on server-sent events implementation in case of using event-source
or XHR polling
in IE 8-10 (which confused me first time). 此外,如果在IE 8-10中使用event-source
或XHR polling
(这使我第一次困惑),有时会在服务器发送的事件实现上发生此类问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.