![](/img/trans.png)
[英]What is the proper way of doing long polling using jQuery and AJAX
[英]What is the best way to do long polling in AJAX requests in JavaScript without JQuery?
在网上搜索如何在JavaScript
使用long polling
,您好,我最后以三种方式进行了介绍, 这里简要介绍了它们,但是它们是使用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
});
有人可以指导我吗?
我想我在这里找到了解决方案
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.