簡體   English   中英

在同一頁面中有多個ajax調用?

[英]more than one ajax call in the same page?

我有以下代碼

function ajaxCall(action,parameters){

if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}else{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

//xmlhttp.overrideMimeType('text/html');

xmlhttp.onreadystatechange=function(){

if (xmlhttp.readyState==4 && xmlhttp.status==200){

var rtrv_data=xmlhttp.responseText;

alert(rtrv_data);



}

}
parameters='action=' + action + '&' + parameters;

xmlhttp.open("POST","ajax_calls.php" ,true);

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xmlhttp.setRequestHeader("Content-length", parameters.length);

xmlhttp.setRequestHeader("Connection", "close");

xmlhttp.send(parameters);

}

假設我有一個定時器調用此函數,並再次點擊該頁面上的函數,我只得到一個輸出! 一個回應! 我能得到2嗎?

謝謝你 。

變量“xmlhttp”是全局的(你沒有使用“var”)所以這永遠不會允許兩個同時的ajax調用,因為當第二個調用開始時你將覆蓋同一個變量,這是在回調中用來檢索數據的變量。

您需要每次創建一個新變量來存儲xml請求對象,並且還需要使用閉包來完成回調...類似於

var xmltthp = ... // this is a local variable

xmlhttp.onReadyStateChange = function() {
    // here you can use xmlhttp even if it's a local
    // it will be a different variable for each ajax request
}

謝謝! 這對我有用! 做過這個:

function refreshpage(){
    var mycode=document.getElementById("bcode").value;
        if (window.XMLHttpRequest){
      xmlhttpf=new XMLHttpRequest();
    }else{
    xmlhttpf=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttpf.onreadystatechange=function(){
        if (xmlhttpf.readyState==4 && xmlhttpf.status==200){
            document.getElementById("zones").innerHTML=xmlhttpf.responseText;
        }
    }
    xmlhttpf.open("GET","ajaxaki.php?code="+mycode,true);
    xmlhttpf.send();
}


function refresh_vehs(){
    var asma=document.getElementById("newasma").value;
        if (window.XMLHttpRequest){
      xmlhttpf_vehs=new XMLHttpRequest();
    }else{
    xmlhttpf_vehs=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttpf_vehs.onreadystatechange=function(){
        if (xmlhttpf_vehs.readyState==4 && xmlhttpf_vehs.status==200){
            document.getElementById("vehicles").innerHTML=xmlhttpf_vehs.responseText;
        }
    }
    xmlhttpf_vehs.open("GET","AJAX_vehicle_cards.php?asma="+asma,true);
    xmlhttpf_vehs.send();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM