简体   繁体   English

JavaScript中的运行顺序命令

[英]Order of Run command in JavaScript

Obviously to talk to a server you would have to first send a request to the server, then recieve the response. 显然,要与服务器通信,您必须先向服务器发送请求,然后接收响应。 However it appears in this code that you first recieve the response then in the next line send the request -- what is going on here? 但是,在此代码中,您似乎首先接收到响应,然后在下一行发送请求-这是怎么回事?

    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","gethint.php?q="+str,true);
    xmlhttp.send();

It doesn't receive the response first, it just sets up what to do when the response is received (which is never immediately, as this is an asynchronous operation). 它不首先接收响应,它只是设置接收响应的处理方式( 永远不会立即执行,因为这是异步操作)。 The order here actually doesn't matter. 实际上,这里的顺序并不重要。

onreadystatechange is just a listener that runs when the request resolves. onreadystatechange只是在请求解析时运行的侦听器

Imagine your friend is helping you collect mail at the post office. 想象一下,您的朋友正在帮助您在邮局收集邮件。 You tell him: 你告诉他:

"Whenever a worker gives you the package, check the name on the package is correct, then open it, assemble the contents, and bring it back to me at my house. Now, go to the post office!" “只要有工人给您包装,请检查包装上的名称是否正确,然后打开包装,装箱,然后将其带回我家。现在,去邮局!”

You've told your friend what to do when he gets your mail, and then you sent him out to go collect it. 您已经告诉您的朋友,当他收到您的邮件时该怎么办, 然后您将他发送出去,以进行收集。

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

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