我有一个 html 页面,部署在 xampp
页面有一个脚本标签,我在其中使用 XMLHttpRequest
调用服务url来获取json数据。
这仅在我使用 http://localhost/mypage
调用页面时有效
但是当我从另一台计算机调用同一页面时http://ipadress/mypage
它会抛出一个错误。
“No 'Access-Control-Allow-Origin' header is present on the requested resource”
我尝试使用JSONP
解决方案,但也不起作用
请注意,我只能操作客户端代码(javascript
),我无法控制我正在调用的服务
为什么它适用于 localhost
但它不适用于 ipadress
?
如果有的话,替代解决方案是什么?
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var result = JSON.parse(this.responseText).result;
document.getElementById("data").innerHTML = result + "%";
}
};
var url = "www.url.com";
xhttp.open("GET", url + "/data.json", true);
xhttp.setRequestHeader("content-type", "application/json");
xhttp.send();
最佳答案
因此,您尝试从与应用程序实际所在域不同的域检索数据。您必须为您的服务页面指定允许这样做。
根据您构建/提供 html 页面/内容 (json) 的方式,这是不同的。
通常这是通过在响应发送回客户端之前在 header 中设置它来完成的。
使用 PHP:header('Access-Control-Allow-Origin: *');
使用 apache .htaccess 文件(对于更多文件,例如:如果不使用服务器端脚本): Header set Access-Control-Allow-Origin "*"
最好不要指定 *,而是指定应用程序应有权访问的来源。
进一步阅读: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
关于javascript - 从另一台计算机调用我的页面时,httprequest 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51005180/