Ajax,多个调用

时间:2010-05-19 05:26:14

标签: ajax

我不知道做多个Ajax calls是一个好习惯吗?

1 个答案:

答案 0 :(得分:1)

进行多次AJAX调用非常棒 - 特别是如果你同时进行这些调用。有很多来源可以做到这一点。这是我使用的:

function ajax(url, params, callback)
{
    var xmlhttp;
    var paramstring = "";
    for (postvar in params)
    {
        if (paramstring.length > 0) paramstring += "&";
        paramstring += postvar + "=" + escape(params[postvar]);
    }
    if (window.XMLHttpRequest)
        xmlhttp = new XMLHttpRequest();
    else if (window.ActiveXObject)
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    else
        throw new exception("XMLHTTPRequest failed to initialize.");
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", paramstring.length);
    xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.onreadystatechange = function ()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) //ok
            callback(unescape(xmlhttp.responseText));
        else if (xmlhttp.readyState==4)
            throw new exception("XMLHTTPRequest loaded with status: " + xmlhttp.status);
    }
    xmlhttp.send(paramstring);
}