Which methods are executed first in an AJAX call?

半城伤御伤魂 提交于 2019-12-25 05:28:16

问题


I have been learning about AJAX and I am a little confused on which order the methods inside an AJAX call are executed. I have seen too many variations. For example

                function submitArticle() {                  

                try {
              //alert("yaay");
                    xhr = new XMLHttpRequest();
                  }
                  catch(e) {
                    try {
                      xhr = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    catch(e) {
                      try {
                          xhr = new ActiveXObject("Msxml2.XMLHTTP");
                      }
                      catch(e) {
                        alert("Your Browser is not Supported");
                        return false;
                      }
                    }    

                  }
              var parameters = "postTitle=" + postTitle "&postDes=" + postDes + "&postCont=" + postDes;    
              xhr.open('POST', '/engine/engine.php', true);      
              xhr.send(parameters);                                  
              xhr.onreadystatechange = function() {
                  if(this.readyState === 4) {
                      if(this.status ===200) {
                         alert(this.responseText);
                      }
                      else {
                        alert("status" + this.status);
                       }
                  }
                  else {
                    alert("readyState" + this.readyState);
                  }
              }


          }

My question is that I have seen code where the open and send methods are placed in a very different spot, like after evaluating the readyState value. Which is the right way to go. I have looked it up on different sites and all i see are jquery tutorials and none of them explained in which order the code will be executed. Sorry if this is a very stupid question or if my code is wrong.


回答1:


Javascript can only call the onreadystatechange callback when control returns to the event loop, after your code finishes running.

Therefore, it doesn't matter whether you add the handler before or after sending the request, as long as you add it in the same unit of synchronous execution.



来源:https://stackoverflow.com/questions/19275333/which-methods-are-executed-first-in-an-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!