Javascript AJAX函数调用延迟

fve*_*rtk 2 javascript php ajax return function

我似乎无法弄清楚如何使这个功能工作.重要的是要看到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();    
}
Run Code Online (Sandbox Code Playgroud)

Tad*_*eck 7

怎么onreadystatechange工作

onreadystatechange事件处理程序 - 作为事件建议的名称 - 在readyState更改时调用.因此,您必须检查状态和状态(就像您在评论的部分中所做的那样).

在此处查看更多详细信息: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
}
Run Code Online (Sandbox Code Playgroud)

因此,您应该编辑代码以使其与此类似(使用readyState/ statusconditions取消注释):

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();    
}
Run Code Online (Sandbox Code Playgroud)

然后就这样使用它:

gettStatus(function(tStat){
    // tStat here is accessible, use it for further actions
});
Run Code Online (Sandbox Code Playgroud)

而不是以下列方式使用它:

var tStat = gettStatus();
// tStat would be available here, if gettStatus() would not involve
// asynchronous requests
Run Code Online (Sandbox Code Playgroud)