gpt4 book ai didi

javascript - Ajax 请求被阻塞

转载 作者:行者123 更新时间:2023-11-30 12:56:38 26 4
gpt4 key购买 nike

我有一个函数可以通过服务器执行 Ajax 请求。该代码有效,但由于某种原因阻止了其余的 js 代码。所以我必须等到请求结束。这真的很奇怪,因为 ajax 本质上是异步的。任何帮助将不胜感激。

这是代码

function initRequest(url)
{
var xmlhttp = null;
if(xmlhttp != null)
{
if(xmlhttp.abort)
xmlhttp.abort();
xmlhttp = null;
};

if(window.XMLHttpRequest) // good browsers
xmlhttp=new XMLHttpRequest();
else if(window.ActiveXObject) // IE
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

if(xmlhttp == null)
return null;

xmlhttp.open("GET",url,false);
xmlhttp.send(null);

if(xmlhttp.status >= 200 && xmlhttp.status < 300)// 2xx is good enough
return xmlhttp.responseText.split("|");
else
return null;
}

我这样称呼这个函数 var res = initRequest('someurl'); 如果(res){ console.log(res); } console.log('这条消息会在请求被处理时出现!!为什么??');

最佳答案

您应该在 XMLHttpRequest 对象上实现 onreadystatechange 回调并检查其中的状态更改,而不是阻塞地等待服务器的响应。每次更改 readyStatus 属性时都会调用此方法,并且(希望)在您调用 xmlhttp.send(...) 之后的某个时候返回 200;

编辑:所以你的代码看起来像

function initRequest(url, onsuccess, onerror) { 
// ...
xmlhttp.onreadystatechange = function () {
if(this.status >= 200 && this.status < 300) {// 2xx is good enough
onsuccess(this.responseText.split("|"));
}
};
xmlhttp.open("GET", url); // its asynchronous by default
xmlhttp.send(null);
}

为了更好地衡量一些有用的链接 http://www.w3.org/TR/XMLHttpRequest1/https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

关于javascript - Ajax 请求被阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18865265/

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