weixin_33720078 2017-06-29 04:38 采纳率: 0%
浏览 20

AJAX代码顺序的差异

I saw most of the AJAX examples in W3school look like this:

function loadDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            document.getElementById("demo").innerHTML = xhttp.responseText; //get response
        }
    };
    xhttp.open("GET", "ajax_info.txt", true);
    xhttp.send(); //send request
}

I changed the order of the code like this:

function loadDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "ajax_info.txt", true);
    xhttp.send(); //send request
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            document.getElementById("demo").innerHTML = xhttp.responseText; //get response
        }
    };
}

and it seems like it works too, and my brain will think second one more logic.

So my question is: Is there any rules on this AJAX code's order? Will it make any differences for the 2 example above in any situation?

  • 写回答

1条回答 默认 最新

  • weixin_33733810 2017-06-29 04:52
    关注

    The AJAX request is handled asynchronously so the order of definition of the callback does not matter.

    I have annotated your code with some notes. The execution order (in this case) will be:

    1 -> 2 -> 3 (Request Triggered) -> 4 (Define callback)
              |
              5 (Callback function called asynchronously every time the request state changes)
              |
              6 Execute logic if request is successful
    

    Steps 1 (Creation of XHR Object), 2 (Opening request) and 3 (sending request) must be in sequence. Step 4 can happen any time after the creation of the object as long as it's before the network response or state change happens.

    Reading up on AJAX and Asynchronous Callbacks in JS will help understand this better. You can start here.

    function loadDoc() {
      //1. Create XHR Object
      var xhttp = new XMLHttpRequest();
      
      //2. Define request parameters
      xhttp.open("GET", "ajax_info.txt", true);
      
      //3. Trigger Request
      xhttp.send();
      
      //4. Define callback for state change
      xhttp.onreadystatechange = function() {
      //5. This code is executed every time the state of the request changes
        if (xhttp.readyState == 4 && xhttp.status == 200) {
          //6. This code executes only if readyState is 4 (request is done) and the http status is 200 (success)
          document.getElementById("demo").innerHTML = xhttp.responseText; //get response
        }
      };
    }

    </div>
    
    评论

报告相同问题?