Javascript 没有jQuery无法进行跨域请求
我正在从事一个web项目,在这个项目中,使用jQuery或其他库/依赖项不是一个选项,因此我尝试复制jQuery用于发出AJAX请求的代码。该项目以前使用jQuery,因此我已将我的替换对象结构化为$.ajax方法,以具有相同的行为,但是我无法让我的方法进行跨域请求。例如,当尝试加载脚本时,我在控制台中遇到此错误Javascript 没有jQuery无法进行跨域请求,javascript,jquery,ajax,Javascript,Jquery,Ajax,我正在从事一个web项目,在这个项目中,使用jQuery或其他库/依赖项不是一个选项,因此我尝试复制jQuery用于发出AJAX请求的代码。该项目以前使用jQuery,因此我已将我的替换对象结构化为$.ajax方法,以具有相同的行为,但是我无法让我的方法进行跨域请求。例如,当尝试加载脚本时,我在控制台中遇到此错误 XMLHttpRequest cannot load <URL>. No 'Access-Control-Allow-Origin' header is present o
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一定在做什么特别的事情
这就是我的$.ajax替换函数目前的脚本编写方式
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;
}
有人能指出我是否遗漏了一些明显的东西吗?我是否还需要手动执行飞行前选项或其他操作?我找到了解决方法。这个问题似乎源于试图加载跨域脚本。jQuery使用$.getScript来实现这一点,实际上只是向页面添加一个脚本,而不是发出跨域HTTP请求 我使用此代码作为该函数的替换
function getScript (url, callback) {
var loadScript = function (url, callback) {
var scrpt = document.createElement("script");
scrpt.setAttribute("type", "text/javascript");
scrpt.src = url;
scrpt.onload = function () {
scrpt.parentNode.removeChild(scrpt);
console.log("Script is ready, firing callback!");
if (callback)
callback();
};
document.body.appendChild(scrpt);
}
var isReady = setInterval(function () {
console.log(document.body);
if (document.body) {
clearInterval(isReady);
loadScript(url, callback);
}
}, 25);
}
由于有人可能会提到这一点,我应该指出,在本例中,我无法控制向其发出跨域请求的服务器。我正在尝试加载跨域脚本,因此在服务器上执行诸如设置访问控制允许Origin*之类的操作将不是一个选项。以前的代码是否使用JSONP,其中通过脚本标记加载资源的url?检查旧代码,看看它是否在$.ajax选项中使用了dataType:'jsonp',如果是这样,您必须更改代码来处理这种类型的请求者,在您的服务器或第三方服务上使用代理。当尝试加载脚本时,例如,我在控制台中遇到此错误,请不要使用xhr加载脚本。。。