简体   繁体   中英

more than one ajax call in the same page?

I have the following code

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

}

Assuming that i have this function called by some timer , and a click on the page called the function again , i only get one output ! one response ! hwo can i get the 2 ?

thanky you .

The variable "xmlhttp" is a global (you used no "var") so this will never allow two simultaneous ajax calls because when the second call starts you will overwrite the same variable and that's the variable that's used inside the callback to retrieve the data.

You need to create a new variable each time to store the xml request object and also you need to use a closure for your completion callback... something like

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
}

Thanks! That worked for me! Did this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM