-2
我在一個Web項目,其中使用jQuery(或其他庫/依賴)是不是一種選擇,所以我試圖複製jQuery使用,使AJAX代碼要求。該項目以前使用jQuery,所以我已經將替換結構構建到$ .ajax()方法中,以獲得相同的行爲,但是我無法獲取我的跨域請求。例如,當試圖在腳本中加載時,我在控制檯中出現此錯誤。不能使跨域請求,而jQuery的
XMLHttpRequest cannot load <URL>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin <URL> is therefore not allowed access.
我熟悉CORS和整個跨域的安全策略和什麼需要,但我感到困惑的是jQuery的如何似乎規避,而我的代碼不能。我在想一定有什麼特別的jQuery在做什麼?
這是我的$。阿賈克斯()替換功能目前是如何腳本。
function ajax (options) {
var request = new XMLHttpRequest();
if ("withCredentials" in request)
request.withCredentials = false;
else if (typeof XDomainRequest !== "undefined")
var request = new XDomainRequest();
options.type = options.type || options.method || "GET";
request.open(options.type.toUpperCase(), options.url, true);
for (var i in options.headers) {
request.setRequestHeader(i, options.headers[i]);
}
if (typeof options.beforeSend == "function")
var go = options.beforeSend(request, options);
if (go == false)
return false;
request.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE) {
var resp = this.responseText;
try {
var body = JSON.parse(resp);
this.responseJSON = body;
}
catch (err) {
var body = resp;
}
if (this.status < 300 && typeof options.success == "function")
options.success(body, this.status, this);
else if (typeof options.error == "function")
options.error(this, this.status, body);
if (typeof options.complete == "function")
options.complete(this, this.status);
}
};
if (typeof options.data == "object" && options.data !== null)
options.data = JSON.stringify(options.data);
if (options.type.toUpperCase() != "GET")
request.send(typeof options.data !== "undefined" ? options.data : null);
else
request.send();
return request;
}
有人可以指出,如果我失去了明顯的東西?我是否需要手動執行OPTIONS pre-flight或什麼?
既然有人可能會提到這一點,那麼我應該指出,在這種情況下,我無法控制正在進行跨域請求的服務器。我正在嘗試加載跨域腳本,因此在服務器上執行諸如設置「Access-Control-Allow-Origin」到「*」的設置不是一個選項。 – Zerkeras
以前的代碼是否使用JSONP,其中通過腳本標記加載資源的URL?檢查舊代碼,看看它是否使用'數據類型:'在'$。阿賈克斯()'選項jsonp'',如果是的話,你將不得不改變周圍的代碼來處理這種類型的請求 –
或任上使用代理您的服務器或第三方服務 – charlietfl