XMLHttpRequest onreadystatechange 调用多次

2022-08-30 19:49:21

我正在php中实现一个登录系统并使用ajax请求。

这是我的要求

hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

hr.onreadystatechange = function() {

    var return_data = hr.responseText;
    if(hr.readyState == 4 && hr.status == 200) {
        alert('is logged');
    }else if (hr.status == 400){
        alert('is not logged');
    }
}


hr.send(vars); // Actually execute the request

但是当我得到回应时,浏览器会启动各种警报。任何人都可以帮助解决这个问题吗?


答案 1

是的,它的工作是应该的。onreadystatechange 可以在一个请求中调用多次。为了提醒这两个条件,条件是每当请求正常时,那就是200

它提醒:

“它未记录”

当它准备就绪时状态=4以及它发出警报:Ok signal

已登录。

然后

readyState =4 -->请求已完成,响应已准备就绪

status= 200 -->表示服务器已成功处理请求。

因此,第二个警报弹出窗口,因为至少您的请求已成功处理。欲了解更多信息: https://www.w3schools.com/js/js_ajax_http_response.asp

这里是:


     xhrobj.onreadystatechange = function()
    {
      if (xhrobj.readyState == 4 && xhrobj.status == 200)
      {
        if (xhrobj.responseText)
         {
                //put your code here 
           document.write(xhrobj.responseText);
          }
       }
     };

答案 2

推荐