連續多次發送Ajax前面的請求被後面的覆蓋以致不能執行的問題

來源:互聯網
上載者:User

標籤:javascript   ajax   

感謝 http://www.jb51.net/article/27610.htm 的文章《ajax同步請求和非同步請求的差異分析》。不過在遇到並解決這個問題之前我也還沒有分清同步非同步差異咳咳~

function fetchdata(cat,str){var xmlHttp;//問題就在這裡    xmlHttp=GetXmlHttpObject();var url;    if(xmlHttp==null)    {        alert("browser doesn‘t support HTTP Request");        return;    }    switch(cat)    {        case "n": url = "getcompany.php?sid="+Math.random();break;        case "c":        case "p": url = "getaddress.php?province="+str+"&sid="+Math.random();break;        case "m": var obj = document.getElementById("deptselect");                  if(obj.value != null && obj.value !="undefined" && obj.value != "")                  {                      alert(obj.value)                      setCookie(‘deptname‘,obj.options[obj.selectedIndex].text,365);                      setCookie(‘deptid‘,str,365);                  }        case "d": url = "deptvsmem.php?deptid="+str+"&sid="+Math.random();break;    }    alert(url)    xmlHttp.onreadystatechange =function() {//非同步呼叫是否成功    if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete")    {        if(xmlHttp.status==200 || xmlHttp.status==0)        {            var sel;var vnum;            var str = xmlHttp.responseText;            alert(str)            switch(str.charAt(0))            {                case "p": sel = "provinceselect";vnum = 1;break;                case "c": sel = "cityselect";vnum = 1;break;                case "n": sel = "comselect";vnum = 1;break;                case "d": sel = "deptselect";vnum = 2;break;                case "m": sel = "memselect";vnum = 2;break;            }            str = str.substr(1);            BuildSel(str,document.getElementById(sel),vnum);        }    }}    xmlHttp.open("GET",url);    xmlHttp.send(null);}

問題就在於第二行的聲明var xmlHTTP,如果放在函數外用作全域變數,就會產生標題的問題,即前面的xhr被後面的請求覆蓋以致只能執行最後一條請求。只要把它拿進去就沒問題了。。。就!沒!問!題!了!!。。。之前看有前輩說是因為在收到xmlHttp.responseText之後沒有及時刪除,要加delete 而且要設成null,不過親測即使刪除了設成null了還是會覆蓋,這樣把聲明放進函數內之後即使沒有刪除也沒問題了。。。@_@

本文出自 “Chronosphere” 部落格,轉載請與作者聯絡!

連續多次發送Ajax前面的請求被後面的覆蓋以致不能執行的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.