从 JavaScript returns 中的回调返回未定义?
Returning from a callback in JavaScript returns undefined?
我有这个代码:
function fetchSocialCount(type,fileSrc,callback){
var req = new XMLHttpRequest();
req.onload = function(){
if(req.status === 200 && req.readyState === 4){
var countResponse = JSON.parse(req.responseText);
callback(countResponse);
}
}
req.open("GET","../scripts/php/returnSocialCount.php",false);
req.send();
}
var test = fetchSocialCount("img","ez.png",function(count){
return count;
});
console.log(test);
但由于某些原因,test
未定义。我的 AJAX 确实有效,它 returns 是一个对象。有什么问题?
您的 test
获得 fetchSocialCount
本身的 return 值,这是未定义的,因为它没有 return 任何东西。
你可以试试这个:
function fetchSocialCount(type, fileSrc) {
var req = new XMLHttpRequest()
, result = null;
req.onload = function(){
if(req.status === 200 && req.readyState === 4){
result = JSON.parse(req.responseText);
}
}
req.open("GET","../scripts/php/returnSocialCount.php",false);
req.send();
return result;
}
由于您使用的是 同步 请求,您应该能够直接 return 它的结果; return实际上,正如@Trolleymusic 在评论中指出的那样,像您所做的那样从回调中调用无济于事
the callback returns to that which called the callback, (in this case
callback(countResponse)
), no further up
我有这个代码:
function fetchSocialCount(type,fileSrc,callback){
var req = new XMLHttpRequest();
req.onload = function(){
if(req.status === 200 && req.readyState === 4){
var countResponse = JSON.parse(req.responseText);
callback(countResponse);
}
}
req.open("GET","../scripts/php/returnSocialCount.php",false);
req.send();
}
var test = fetchSocialCount("img","ez.png",function(count){
return count;
});
console.log(test);
但由于某些原因,test
未定义。我的 AJAX 确实有效,它 returns 是一个对象。有什么问题?
您的 test
获得 fetchSocialCount
本身的 return 值,这是未定义的,因为它没有 return 任何东西。
你可以试试这个:
function fetchSocialCount(type, fileSrc) {
var req = new XMLHttpRequest()
, result = null;
req.onload = function(){
if(req.status === 200 && req.readyState === 4){
result = JSON.parse(req.responseText);
}
}
req.open("GET","../scripts/php/returnSocialCount.php",false);
req.send();
return result;
}
由于您使用的是 同步 请求,您应该能够直接 return 它的结果; return实际上,正如@Trolleymusic 在评论中指出的那样,像您所做的那样从回调中调用无济于事
the callback returns to that which called the callback, (in this case
callback(countResponse)
), no further up