[英]xhr request Control Origin
我正在嘗試獲取xhr請求。 (腳本應每2秒循環運行一次)這是我的腳本:
function getJson() {
var xhr = new XMLHttpRequest();
xhr.open("get", "http://www.oref.org.il/WarningMessages/alerts.json", true);
xhr.onload = function(){
var response = JSON.parse(xhr.responseText);
checkJson(response);
}
xhr.send(null);
setTimeout(arguments.callee, 2000);
}
getJson();
我收到此錯誤: XMLHttpRequest cannot load http://www.oref.org.il/WarningMessages/alerts.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://klh-dev.com' is therefore not allowed access.
XMLHttpRequest cannot load http://www.oref.org.il/WarningMessages/alerts.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://klh-dev.com' is therefore not allowed access.
因此,我在線搜索,嘗試在腳本中添加幾行,但沒有成功: response.addHeader("Access-Control-Allow-Origin", "http://www.oref.org.il/WarningMessages");
response.addHeader("Access-Control-Allow-Origin", "*");
我在外部html頁面中嘗試了這個
header('Access-Control-Allow-Origin: *');
什么都沒用..
您遇到了一系列問題,這些問題統稱為跨源資源共享(CORS)。 長話短說,瀏覽器通常不允許腳本訪問不是腳本源的服務器,除非服務器明確允許。 由於腳本的來源http://klh-dev.com
與請求目標http://www.oref.org.il
,因此瀏覽器阻止了該請求。
有兩種可能的解決方案:1)修改服務器以實現CORS標頭(除非您在服務器的控制下,否則可能無法實現)或2)使用JSONP執行請求(並非在所有情況下均有效)。 那么,JSONP還是CORS?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.