简体   繁体   中英

multiple ajax calls using only javascript

isn't it possible to execute multiple ajax calls using javascript only and without using Jquery. I tried the below javascript code with two ajax calls but the code is not working when I place the second ajax call

<script type="text/javascript">

var class1;
var class2;
var sec1;
var sec2;

function func()
{
class1 = document.getElementById('selcla');
class2 = class1.options[class1.selectedIndex].value;

if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
      }
else
      {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
xmlhttp.onreadystatechange=function()
      {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("secdiv").innerHTML=xmlhttp.responseText;
        }
      }
xmlhttp.open("GET","getsec.php?q="+class2,true);
xmlhttp.send();

}


function funcsec()
{
sec1 = document.getElementById('selsec');
sec2 = sec1.options[sec1.selectedIndex].value;
alert("selecting class and section details " + class2 + " " + sec2 );

    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
      }
else
      {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }

xmlhttp.onreadystatechange=function()
      {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        alert("successfully received " );
        document.getElementById("studiv").innerHTML=xmlhttp.responseText;
        }
    else 
        alert("unsuccessful ajax second call ");
      }
xmlhttp.open("GET","getstu.php?x="+class2"&y="+sec2,true);
xmlhttp.send();
}

It is, but you need a different "xmlhttp" handler for each request you make. Setup a new xmlhttp object and make a second request with the new object.

My suggestion is to break out the part with you initializing the xmlhttp object, into a standalone function, and use it to create a few instances of those objects.

However I must advise against such an approach. It is better to use a library for ajax requests.

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