我嘗試使用下面的代碼來拉從一個API的數據並運行它在一個HTML頁面上的Firefox:使用Javascript的跨源API請求?
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
url = 'https://xxxx.xxx?p=api';
xobj.open('GET', url, true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200")
parsedjson = xobj.responseText;
parsedjson = JSON.parse(parsedjson);
,但我得到了以下錯誤:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxxx.xxx?p=api . (Reason: CORS header 'Access-Control-Allow-Origin' missing).
而下面響應報頭(狀態:302):
Cache-Control: private
Content-Length: 502
Content-Type: text/html; charset=utf-8
Date: <Scrubbed>
Location: https://xxxx.xxx?p=api&additionalparameter=data
Server: <Scrubbed>
Set-Cookie: value: path=/; secure; HttpOnly
<Scrubbed>
X-AspNet-Version: <Scrubbed>
X-Frame-Options: SAMEORIGIN
X-Powered-By: ASP.NET
X-UA-Compatible: IE=edge
x-href: <Scrubbed>
這可能是需要了解的是,請求報頭包含:
Origin: null
我讀過關於JSONP和CORS - 但不知道在這裏適用,以及如何使用。我如何更新我的代碼以獲取數據?請注意,我無法控制服務器,但是如果通過瀏覽器訪問數據,我可以訪問數據。
我也讀過一個選項是建立我自己的小型服務器。這可能會起作用,但這個項目的要求是使它成爲客戶端(所以我可以與其他人共享js/html文檔,並且他們可以插入&而不必設置他們自己的服務器...
可能重複[「No'Access-Control-Allow-Origin'標頭出現在請求的資源」](http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header- is-present-on-the-requested-resources) – Tushar
可能 - 這個問題是在Jquery中,但這是純粹的JavaScript,也沒有給我一個解決方案的答案 – SimaPro