0

在验证发送传真表单时,我正在检查是否已经使用我们的软件传真包发送了传真。这是一个由脚本执行的对表的简单查询,如果存在先前的传真,则返回一些文本,否则返回空白。

我发现 flag_stop_fax 变量仍然设置为零,即使我有一些响应文本(例如:“传真已经发送。”)。

flag_stop_fax = 0;
xmlhttp.onreadystatechange=function() 
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    {
        var response = xmlhttp.responseText;
        if (response!='')
        {
            flag_stop_fax = 1;
            alert(response);
        }
    }
}

xmlhttp.open('GET','/check_for_active_fax.php?fax_number=' + fax_number + '&t='+Math.random(),true);
xmlhttp.send();

alert(flag_stop_fax); // shows "0" even when I have a non-blank response from xmlhttp.responseText

还有一些其他的验证位,但上面的脚本希望能说明这个问题。我不会将 't' 变量用于任何事情 - 这只是防止浏览器缓存的保护措施。

那么为什么我的 flag_stop_fax 没有设置为 0?

4

1 回答 1

0

首先您必须了解 AJAX 是异步的。当你执行时xmlhttp.send();,你的请求被发送并且代码继续执行,所以接下来要运行的是:

alert(flag_stop_fax);

此时,flag_stop_fax仍然为零,因为请求还没有完成。

您指定的回调函数xmlhttp.onreadystatechange只会在请求完成时运行。这里的执行不是顺序的。它是这样的:

  1. xmlhttp.send();- 请求已经开始
  2. alert(flag_stop_fax);- 变量被警告

    ...
    ...
    (一段时间后,当服务器回答时)

    xmlhttp.onreadystatechange被执行,改变flag_stop_fax变量。

于 2012-10-29T18:42:44.110 回答