嗨,在网上搜索如何在 JavaScript
中使用长轮询
后,我最终找到了三种方法,其中提到了 here简单来说,它们是使用 JQuery 实现的。如果我发送到服务器的 AJAX 请求是异步 GET 请求,我很困惑该使用哪一个,而且我不知道它可能需要多少时间。
这是一个 AJAX 请求示例:
function asynchGETRequest(method,url){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("ok");
}
};
xhttp.open(method, url, true);
xhttp.send();
return (xhttp.responseText);
}
var clientFunctions={
getAnswers : function(callback){
var res=asynchGETRequest("GET", "http://localhost:9000/answers");
callback(JSON.stringify(res));
}
}
clientFunctions.getAnswers (function(){
//do some code here after the ajax request is ended
});
有人可以指导我吗?
最佳答案
我想我找到了解决方案 here
function loadFile(sUrl, timeout, callback){
var args = arguments.slice(3);
var xhr = new XMLHttpRequest();
xhr.ontimeout = function () {
console.error("The request for " + url + " timed out.");
};
xhr.onload = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
callback.apply(xhr, args);
} else {
console.error(xhr.statusText);
}
}
};
xhr.open("GET", url, true);
xhr.timeout = timeout;
xhr.send(null);
}
关于javascript - 在没有 JQuery 的 JavaScript 中,在 AJAX 请求中进行长轮询的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45976161/