如何在JavaScript中强制程序等待HTTP请求完成? [英] How to force a program to wait until an HTTP request is finished in JavaScript?

查看:629
本文介绍了如何在JavaScript中强制程序等待HTTP请求完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

有什么想法吗?

预先感谢您, Thanasis

Thank you in advance, Thanasis

推荐答案

XmlHttpRequestopen()有一个第3个参数,旨在指示您希望异步请求(并因此处理响应)通过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请求完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆