如何强制程序等到 JavaScript 中的 HTTP 请求完成?

时间:2023-05-14
本文介绍了如何强制程序等到 JavaScript 中的 HTTP 请求完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在 JavaScript 中有没有办法向 HTTP 服务器发送 HTTP 请求并等待服务器响应?我希望我的程序等到服务器回复而不执行此请求之后的任何其他命令.如果 HTTP 服务器宕机了,我希望 HTTP 请求在超时后重复,直到服务器回复,然后程序的执行才能正常继续.

Is there a way in JavaScript to send an HTTP request to an HTTP server and wait until the server responds with a reply? I want my program to wait until the server replies and not to execute any other command that is after this request. If the HTTP server is down I want the HTTP request to be repeated after a timeout until the server replies, and then the execution of the program can continue normally.

有什么想法吗?

提前谢谢你,塔纳西斯

推荐答案

XmlHttpRequestopen()有第三个参数,目的是表明你希望异步请求(因此通过 onreadystatechange 处理程序处理响应).

There is a 3rd parameter to XmlHttpRequest's open(), which aims to indicate that you want the request to by asynchronous (and so handle the response through an onreadystatechange handler).

因此,如果您希望它是同步的(即等待答案),只需将此第三个参数指定为 false.在这种情况下,您可能还想为您的请求设置一个有限的 timeout 属性,因为它会阻塞页面直到接收到.

So if you want it to be synchronous (i.e. wait for the answer), just specify false for this 3rd argument. You may also want to set a limited timeout property for your request in this case, as it would block the page until reception.

这是一个同步和异步的一体化示例函数:

Here is an all-in-one sample function for both sync and async:

function httpRequest(address, reqType, asyncProc) {
  var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
  if (asyncProc) { 
    req.onreadystatechange = function() { 
      if (this.readyState == 4) {
        asyncProc(this);
      } 
    };
  } else { 
    req.timeout = 4000;  // Reduce default 2mn-like timeout to 4 s if synchronous
  }
  req.open(reqType, address, !(!asyncProc));
  req.send();
  return req;
}

你可以这样称呼:

var req = httpRequest("http://example.com/aPageToTestForExistence.html", "HEAD");  // In this example you don't want to GET the full page contents
alert(req.status == 200 ? "found!" : "failed");  // We didn't provided an async proc so this will be executed after request completion only

这篇关于如何强制程序等到 JavaScript 中的 HTTP 请求完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何判断 XMLHTTPRequest 是否命中浏览器缓存 下一篇:XMLHttpRequest responseType = "json";给出错误 SYNTAX_E

相关文章