求一个js回调函数的写法(非常紧急在线等)

shaosun0525 2014-08-17 01:58:32
我想把 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;


}
...全文
402 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
天际的海浪 2014-08-17
  • 打赏
  • 举报
回复
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);//这里获取回调结果 })
ty0415 2014-08-17
  • 打赏
  • 举报
回复
兄弟,ajax是异步请求。所以赋值的时候相当于还没给returnObj赋值,就已经返回回去了。
yaotomo 2014-08-17
  • 打赏
  • 举报
回复
if (xhr.readyState == 4 && xhr.status == 200) { alert(xhr.response); } 上面代码显示xhr.response值为多少?

87,901

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧