为什么这个JavaScript方法返回undefined? [英] why this JavaScript method return undefined?
本文介绍了为什么这个JavaScript方法返回undefined?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这段代码中这个方法返回undefined despites alert语句打印一个值?
in this code this method return undefined despites alert statement print a value ?
function getNearestPoint(idd)
{
var xmlhttp;
var result;
if(window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
result= xmlhttp.responseText;
alert(result);
}
}
xmlhttp.open("GET","ajax_get_nearest_location.php?id="+idd +"&radius=1",true);
xmlhttp.send();
return result;
}
推荐答案
结果未定义于这一点,它只在你的回调执行后才被定义。执行顺序:
result isn't defined at that point, it only gets defined once your callback executes. The order of execution:
-
getNearestPoint
启动 - XHR被解雇
-
getNearestPoint
返回undefiend
- XHR返回并运行
xmlhttp.onreadystatechange
- 结果设置
getNearestPoint
starts- XHR is fired off
getNearestPoint
returnsundefiend
- XHR comes back and runs
xmlhttp.onreadystatechange
- result gets set
如果你需要来自OUTSIDE的结果,你应该使用回调:
If you need result from OUTSIDE of this, you should use a callback:
getNearestPoint(idd, cb){
...
xmlhttp.onreadystatechange = function(){
...
cb(result);
}
}
并且您的主叫代码更改为:
and your calling code changes from:
var result = getNearestPoint(id);
to:
getNearestPoint(id, function(result){
// do something with result;
});
这篇关于为什么这个JavaScript方法返回undefined?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文