gpt4 book ai didi

javascript - 不使用jQuery发送跨域ajax请求

转载 作者:太空宇宙 更新时间:2023-11-03 21:57:10 25 4
gpt4 key购买 nike

我有以下代码:

function ajax(callback, requestString){
console.log("basic ajax sending");
var xmlhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
callback(xmlhttp.responseText); //we got a response
}
}

xmlhttp.open("GET", requestString, true);
xmlhttp.send();

}
//Here: code to be able to use that function repeatedly.

如果在我的node.js服务器的域上使用它效果很好,问题是我正在开发一个API,并且请求必须跨域发送。这些请求(requestString)只是一个字符串,其格式类似于:“http://example.com/r?a=a”+“&b=b”(如果有的话)。我收到以下错误: XMLHttpRequest 无法加载。仅协议(protocol)方案支持跨源请求:http、data、chrome、chrome-extension、https、chrome-extension-resource。我确实看到了 jQuery 和 jsonP 的解决方案,但我不想将 jQuery 推给我的客户,所以我必须找到一个好的解决方案......感谢您的宝贵时间!

最佳答案

但是 jsonP 可以在没有 jQuery 的情况下工作。例如:

var CallbackRegistry = {};

function scriptRequest(url, onSuccess, onError) {
var scriptOk = false;
// generating JSONP function name
var callbackName = 'cb' + String(Math.random()).slice(-6);
// add name in url
url += ~url.indexOf('?') ? '&' : '?';
url += 'callback=CallbackRegistry.' + callbackName;
CallbackRegistry[callbackName] = function (data) {
scriptOk = true;
delete CallbackRegistry[callbackName];
onSuccess(data);
};
function checkCallback() {
if (scriptOk) return;
delete CallbackRegistry[callbackName];
onError(url);
}
var script = document.createElement('script');
// for IE
script.onreadystatechange = function () {
if (this.readyState == 'complete' || this.readyState == 'loaded') {
this.onreadystatechange = null;
setTimeout(checkCallback, 0);
}
}
script.onload = script.onerror = checkCallback;
script.src = url;
document.head.appendChild(script);
}

现在您只需调用即可通过跨域获得响应

function afterSuccess(data) {
alert('Success' + data);
}
function afterError(data) {
alert('Error' + data);
}

scriptRequest(url, afterSuccess, afterError);

关于javascript - 不使用jQuery发送跨域ajax请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37603098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com