我似乎不知道如何让这个函数工作。需要注意的关键是tStat=xmlhttp2.responseText似乎被延迟了。我让它用.innerHTML+="withintest"+Stat来测试这一点。它打印出"在最内部,在最内部0"。所以它会进行几次迭代,直到它有了值??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
的工作原理
readyState
更改时会调用onreadystatechange
事件处理程序(正如事件名称所示)。因此,您必须检查状态和状态(就像您在评论部分所做的那样)。
点击此处查看更多详细信息:Mozilla开发者网络:AJAX-入门
readyState
值列表
从上面引用的页面(链接到该部分):
readyState值的完整列表如下:
- 0(未初始化)
- 1(加载)
- 2(已加载)
- 3(交互式)
- 4(完整)
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
您注释掉的行用于过滤readystates。
/*if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{*/
tStat=xmlhttp2.responseText;
document.getElementById("txtHint").innerHTML+=" withintest "+tStat;
return tStat;
//}
应该是
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
tStat=xmlhttp2.responseText;
document.getElementById("txtHint").innerHTML+=" withintest "+tStat;
return tStat;
}