weixin_33743703 2016-04-28 01:36 采纳率: 0%
浏览 3

解释Ajax代码顺序

I use Ajax a lot for my web projects but just now I want to fully understand it. I got into this problem.

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
}

Look at the code. In my logic I think we have to send request first then get response later. So why in ajax code we get response before send request. Am I missing something here? Thank you in advance!

  • 写回答

1条回答 默认 最新

  • weixin_33709364 2016-04-28 01:44
    关注

    This part:

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

    is defining a callback function (asynchronous). This function is only called when your xmlhttprequest object changes state (you attached it to the onreadystatechange event). You need to define the callback function before you make the call itself (xhttp.open) otherwise it won't know what to do, but the code itself does not run until the state of the xmlrequestobject changes.

    评论

报告相同问题?