简体   繁体   English

为什么我们在AJAX中处理请求之前的响应?

[英]Why we handle the response before the request in AJAX?

I am new to AJAX, As i understood that the handler function executes when response is ready. 我是AJAX的新手,据我了解,处理程序功能在响应准备就绪时执行。

  xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
          document.getElementById("demo").innerHTML =
          this.responseText;
      }
   };

And then we create and send our request 然后我们创建并发送请求

xhttp.open("GET", url, true);
xhttp.send();

does it make sense to handle the response while not sending the request yet !? 在不发送请求的情况下处理响应是否有意义!? Thanks 谢谢

It makes sense because we may get the response while the response event handler was not set. 这是有道理的,因为我们可能在未设置响应事件处理程序的情况下获得了响应。 Also, we do not handle the response right away, but we define the handler function which deals with the response. 同样,我们不会立即handle the response ,但是会定义handle the response的处理函数。

On the other hand, in 99% of cases one will make no mistake to define the handler after the send() , in case he does not care whether the request failed immediately. 另一方面,在99%的情况下,在send()之后定义处理程序时不会出错,以防他不在乎请求是否立即失败。

So, if there is no other way, than define the response handler after sending the request, but in all other cases do it a proper and secure way - before. 因此,如果没有其他方法,除了在发送请求后定义响应处理程序外,在其他所有情况下,请在之前进行正确且安全的处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM