Sending two Ajax requests to two different PHP scr

2020-07-27 04:29发布

问题:

Is it possible to send Ajax requests to two or more Php scripts simultaneously? I know that this can be achieved serially (getting response from 1 and then getting response from the other) but I am wondering is it possible simultaneously. Please assist me with the following code:

function calShowUpload(){
    if (http.readyState == 4) {
        res = http.responseText;
        document.getElementById('maincontent').innerHTML=res;
    }
}

function showUpload(obj)
{
      http.open("GET", "./showUpload.php", true);
    http.onreadystatechange = calShowUpload;
    http.send(null);
}


function getXHTTP() {
    var xhttp;
    try {   // The following "try" blocks get the XMLHTTP object for various browsers…
            xhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } 
    catch (e) {
            try {
            xhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } 
        catch (e2) {
         // This block handles Mozilla/Firefox browsers...
                try {
                    xhttp = new XMLHttpRequest();
                } 
            catch (e3) {
                    xhttp = false;
                }
            }
        }
    return xhttp; // Return the XMLHTTP object
}

var http = getXHTTP(); // This executes when the page first loads.

In the above example I know that I can call another function like showUpload(obj) inside calShowUpload() to achieve my objective, but I need something like this:

function showUpload(obj)
{
      http.open("GET", "./showUpload.php", true);
      http.open("GET", "./showDelete.php", true);
    http.onreadystatechange = calShowUpload;
    http.send(null);
}

回答1:

You need two instances of the XMLHttpRequest or the second will stomp the first. The very, very easiest way to do this with your existing code is simply to create two instances and write your JS to use whichever one is appropriate to the task.

var http1 = getXHTTP(); // Use this for one request.
var http2 = getXHTTP(); // Use this for the other request.