Ajax question
I am learning Ajax at the moment. The code below basically gets an echo from PHP and then puts it in the element id games
.
My question is, if I wanted Ajax to send 3 different HTTP requests to 3 different PHP scripts, and if I wanted to get data from each of them and then put it in 3 different element IDs, I would make 3 copies is this the same function? I would suggest there must be a more 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();
}
+2
a source to share
2 answers
There is no need to do this. You just need 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();
}
+6
a source to share
There is. Use a JavaScript framework like jQuery , Prototype, or whatever. They all have built-in Ajax functionality that makes the things you want to do a lot easier.
Example jQuery Ajax Request:
$('#games').load('hw9.database.php?name=' + str );
+1
a source to share