我似乎无法弄清楚如何让这个功能发挥作用。需要注意的关键是 tStat = xmlhttp2.responseText 似乎被延迟了。我用 .innerHTML +="withintest "+Stat 对此进行了测试。它打印出“withintest withintest withintest 0”。所以它会进行几次迭代直到它具有值(value)? 0 是我想要的 Stat 值,checktStatus.php 从数据库中获取它。
但是由于此函数返回一个值,并且我将它从另一个函数调用到该值的变量中,因此不能在返回之前延迟 DB 读取。但我无法弄清楚如何实现这一目标!帮助?
编辑:删除了一些注释代码,但问题仍然存在。它在获得真实值之前返回一个“未定义”值。
function gettStatus()
{
var tStat;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
tStat=xmlhttp2.responseText;
document.getElementById("txtHint").innerHTML+=" withintest "+tStat;
return tStat;
}
}
xmlhttp2.open("GET","checktStatus.php?tID=1",true);
xmlhttp2.send();
}
最佳答案
onreadystatechange
的工作原理
onreadystatechange
事件处理程序 - 如事件名称所示 - 在 readyState
更改时调用。因此,您必须检查状态和状态(就像您在评论部分所做的那样)。
在此处查看更多详细信息:Mozilla Developer Network: AJAX - Getting Started
readyState
值列表
来自上面引用的页面 ( link to the section ):
The full list of the readyState values is as follows:
- 0 (uninitialized)
- 1 (loading)
- 2 (loaded)
- 3 (interactive)
- 4 (complete)
AJAX 的异步特性
您还应该知道,通常 AJAX 是异步工作的,因此只传递一旦收到响应就会执行的回调对您来说会更容易,就像这样:
function gettStatus(callback){
// do something here...
callback(result); // ...and execute callback passing the result
}
解决方案
因此,您应该编辑您的代码,使其看起来与此类似(readyState
/status
条件未注释):
function gettStatus(callback)
{
var tStat;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
tStat=xmlhttp2.responseText;
document.getElementById("txtHint").innerHTML+=" withintest "+tStat;
callback(tStat);
}
}
xmlhttp2.open("GET","checktStatus.php?tID=1",true);
xmlhttp2.send();
}
然后就这样使用它:
gettStatus(function(tStat){
// tStat here is accessible, use it for further actions
});
而不是以下列方式使用它:
var tStat = gettStatus();
// tStat would be available here, if gettStatus() would not involve
// asynchronous requests
关于php - Javascript AJAX 函数调用延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9258385/