我一直在阅读有关回调函数的信息,并正在尝试使用它。但我看不到它的好处。以我下面的代码为例,我看不出#1 和#2 之间的区别。而是#1似乎毫无意义
1:
function serverConnect(callback){
//Connecting to server
var xmlhttp;
var getString;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var url="server/topHouses.php";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
//Storing response from server, an array encoded by json
getString = $.parseJSON(xmlhttp.responseText);
callback(getString);
}
}
xmlhttp.send();
}
function doStuff(string){
//do stuff
}
serverConnect(doStuff);
2:
function serverConnect(){
//skip skip skip
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
//Storing response from server, an array encoded by json
getString = $.parseJSON(xmlhttp.responseText);
doStuff(getString);
}
}
function doStuff(string){
//do stuff
}
serverConnect();