weixin_33749131 2013-09-18 06:26 采纳率: 0%
浏览 341

Ajax请求被阻止

I have a function to perform Ajax requests with a server. The code works but for some reason is blocking the rest of js code. So I have to wait until the request is over. This is really strange as ajax is asynchronous in nature. Any help will be appreciated.

Here's the code

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; 
}

and I call this function like this var res = initRequest('someurl'); if(res) { console.log(res); } console.log('this message will appear when the request is served!! WHY??');

  • 写回答

3条回答 默认 最新

  • weixin_33716941 2013-09-18 06:31
    关注

    You should implement the onreadystatechange callback on the XMLHttpRequest object and check for status changes in there, instead of waiting blockingly for the response of your server. This method is going to be called for each change of the readyStatus property and will (hopefully) return 200 at some point, after you called xmlhttp.send(...);

    Edit: So your code would look like

    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); 
    }
    

    For good measure some helpful links http://www.w3.org/TR/XMLHttpRequest1/ and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog