如何检查ajax代码是否执行?

时间:2018-06-19 04:16:00

标签: javascript ajax

如何了解ajax代码中调用的文件是否已执行?

function get_data(radioAns) 
{
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function()
    {
        if (this.readyState == 4 && this.status == 200) 
        {
            document.getElementById("dataExchange").innerHTML =this.responseText;
        }
    };
    xhttp.open("GET","example.php?radioAns="+radioAns, true);
    xhttp.send();
}

这是我的ajax代码.. 我想知道如何检查是否调用了example.php文件。

1 个答案:

答案 0 :(得分:1)

您需要将readyStatestatus的支票分开。

readyState 4(如果您喜欢常量,则为XMLHttpRequest.DONE)表示请求已完成(成功或出错)。

状态[200, 300)通常被认为是成功的。 [300, 400)通常表示某种无内容响应(如重定向)。任何等于或大于400的内容都是错误的。

请参阅https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

考虑到所有这些,请考虑

之类的内容
xhttp.onreadystatechange = function() {
  if (this.readyState === XMLHttpRequest.DONE) {
    if (this.status >= 200 && this.status < 300) {
      // success
    }
    if (this.status >= 400) {
      // error
    }
  }
  // else, the request has not completed *yet*
}