关于Ajax的问题

Str*_*rry 2 ajax

我现在正在学习Ajax.下面的代码基本上接收来自PHP的echo,然后将它放在元素id中games.

我的问题是,如果我想让Ajax向3个不同的PHP脚本发送3个不同的HTTP请求,并且如果我想从每个脚本中检索数据然后将它放在3个不同的元素id中,那么我会为同一个函数制作3个副本吗?我想应该有一种更有效的方式.

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();
}
Run Code Online (Sandbox Code Playgroud)

Pra*_*ana 6

没有必要这样做.你只需要参数化函数:

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();
}
Run Code Online (Sandbox Code Playgroud)