开发者

AJAX: How to use TWO xmlHttpRequest in parallel in ONE function?

开发者 https://www.devze.com 2023-01-13 07:00 出处:网络
How should I do this? funct开发者_StackOverflow社区ion(id,id2){ if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari

How should I do this?

funct开发者_StackOverflow社区ion(id,id2){

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

First Request:

   xmlhttp.open("GET", "http://example.com/ajax.php?id="+id, true);

   xmlhttp.send();

Second Request:

   xmlhttp.open("GET", "http://example.com/ajax2.php?id2="+id2, true);

   xmlhttp.send();

}

Because in this way doesn't works.

I want to make it in plain javascript, so please do not post answers with jQuery or any library etc.

Thanks


It should work if you create a new xmlhttp object. Currently you are attempting to reuse the same object, which is already performing a query so it will not work.


if you are looking for classic javascript style you can use as the following. But use jQuery as it's simple and comprehensive. The one thing to be noted is that the "xmlhr" should be in method (callAjax) scope.

function callAjax(url) {
        var xmlhr;

        if (window.XMLHttpRequest) {
            xmlhr = new XMLHttpRequest();
        } else {
            xmlhr = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhr.onreadystatechange = function () {
            if (xmlhr.readyState == 4 && xmlhr.status == 200) {
                alert(xmlhr.responseText);
            }
        }
        xmlhr.open("GET", url, true);
        xmlhr.send();
    }

    function myFunction(id1, id2) {
        callAjax("http://example.com/ajax2.php?id2=" + id1);
        callAjax("http://example.com/ajax2.php?id2=" + id2);
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消