js回调函数的写法(非常紧急)
求一个js回调函数的写法(非常紧急在线等)
我想把 xhr.response作为返回值付给 returnObj 然后返回,但是一直返回“”空,但是alert出来 alert(xhr.response);是有值的,怎么修改程序呀,请大家帮忙看看,我需要getJsonByURL能返回xhr.response这个值,不知道如何实现
getJsonByURL:function(type,url,nickName){
var returnObj="";
var xhr = cc.loader.getXMLHttpRequest();
xhr.open(type, url);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
returnObj=xhr.response;
}
};
return returnObj;
}
------解决方案--------------------
兄弟,ajax是异步请求。所以赋值的时候相当于还没给returnObj赋值,就已经返回回去了。
------解决方案--------------------
getJsonByURL:function(type,url,nickName,returnFun){
var xhr = cc.loader.getXMLHttpRequest();
xhr.open(type, url);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
returnFun(xhr.response);
}
};
}
//使用方法
xxx.getJsonByURL(type,url,nickName,function(str){
alert(str);//这里获取回调结果
})
我想把 xhr.response作为返回值付给 returnObj 然后返回,但是一直返回“”空,但是alert出来 alert(xhr.response);是有值的,怎么修改程序呀,请大家帮忙看看,我需要getJsonByURL能返回xhr.response这个值,不知道如何实现
getJsonByURL:function(type,url,nickName){
var returnObj="";
var xhr = cc.loader.getXMLHttpRequest();
xhr.open(type, url);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
returnObj=xhr.response;
}
};
return returnObj;
}
------解决方案--------------------
兄弟,ajax是异步请求。所以赋值的时候相当于还没给returnObj赋值,就已经返回回去了。
------解决方案--------------------
getJsonByURL:function(type,url,nickName,returnFun){
var xhr = cc.loader.getXMLHttpRequest();
xhr.open(type, url);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
returnFun(xhr.response);
}
};
}
//使用方法
xxx.getJsonByURL(type,url,nickName,function(str){
alert(str);//这里获取回调结果
})