問題描述
在 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.
有什么想法嗎?
提前謝謝你,塔納西斯
推薦答案
XmlHttpRequest
的open()
有第三個參數,目的是表明你希望異步請求(因此通過 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 請求完成?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!