2017-08-31 73 views
0

在網絡中搜索關於如何使用long pollingJavaScript後hi我結束了三種方式,他們簡單地提到here,但他們是用JQuery實現的。如果我發送給服務器的AJAX請求是異步GET請求,我不知道要使用哪一個,並且我不知道需要多少時間。在沒有JQuery的JavaScript中進行AJAX請求的長輪詢的最佳方式是什麼?

這裏有一個例子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 
}); 

可以有人指導我好嗎?

回答

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); 
} 
相關問題