开发者

Question about Ajax

I'm learning Ajax at the moment. The code below basically receives the echo from the PHP and then puts it in element id games.

My question is, if I wanted to have Ajax send 3 different HTTP requests to 3 different PHP scripts and if I wanted to retrieve data from each one and then put it in 3 different element id's then would I make 3 copies of this same function? I would imagine that there should be a mo开发者_开发百科re efficient way.

function showHint(str) {
    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
    } else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("games").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","hw9.database.php?name="+str,true);
    xmlhttp.send();
}


There is no need to do that. You just have to parameterize the function:

function showHint(elementid,url,str) {

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

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById(elementid).innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET",url+str,true);
    xmlhttp.send();
}


There is. Use a JavaScript framework like jQuery, Prototype or any other. All of them have built-in Ajax functionality that makes the things you want to accomplish a lot easier.

Example jQuery Ajax request:

$('#games').load('hw9.database.php?name=' + str );
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜