我有一个函数 isOnline(),如下所示:
function isOnline() {
var request=new XMLHttpRequest();
request.onreadystatechange=function() {
if(request.readyState==4) {
if(request.responseText=="online")
return true;
}
}
request.open("GET","onlinecheck.php?user=user",false);
request.send();
return false;
}
如果我运行 document.write(isOnline());
对于测试,我总是得到 false,(如果我不写 return false;
,则未定义,我得到未定义。
如何在readyState为4之前“等待”并在之后返回true?
最佳答案
您需要关注以下几件事:
onreadystatechange
在发送异步请求时使用 - more here .因此,如果您尝试发送异步请求,请在调用中使用
async=true
- 了解更多 here .request.open("GET", "onlinecheck.php?user=user", true);
最后,如果您要使用异步调用,则不能返回值。检查这两个链接
如果您决定同步执行:
function isOnline() {
var request=new XMLHttpRequest();
request.open("GET","www.google.com/",false);
request.send();
/* check the readyState, you can also check for status code */
if (request.readyState === 4)
// put other conditions here if you need to
return true;
else
return false;
}
// It returns true
关于javascript - XMLHttpRequest() 在函数中返回响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26901972/