0

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.

4

1 回答 1

1

Javascript 只能onreadystatechange在您的代码运行完毕后,当控件返回事件循环时调用回调。

因此,无论是在发送请求之前还是之后添加处理程序,只要在同步执行的同一单元中添加即可。

于 2013-10-09T14:51:36.553 回答