【问题标题】:What is the best way to do long polling in AJAX requests in JavaScript without JQuery?在没有 JQuery 的 JavaScript 中,在 AJAX 请求中进行长轮询的最佳方法是什么?
【发布时间】:2017-08-31 07:55:08
【问题描述】:

嗨,在网上搜索了如何使用JavaScript中的long polling后,我最终得出了三种方法,它们被简单地提到了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
 });

有人可以指导我吗?

【问题讨论】:

    标签: javascript ajax long-polling


    【解决方案1】:

    我想我找到了解决方案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);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-01
      • 2012-07-10
      • 1970-01-01
      • 2017-04-12
      • 2012-04-18
      • 2011-12-29
      • 2012-03-30
      • 1970-01-01
      • 2017-11-01
      相关资源
      最近更新 更多