2015-12-18 7 views
5

Ho una funzione JavaScript per chiamare ajax. Ora ho bisogno di aggiungere il timeout in questa funzione, come quando il servizio di chiamata ha richiesto più tempo di defilare che la chiamata ajax dovrebbe scadere e visualizzare un messaggio predefinito. Non voglio usare Jquery in esso.impostato il timeout nella chiamata ajax durante l'utilizzo di core javascript

Ecco il mio codice:

AJAX = function (url, callback, params) { 
     var dt = new Date(); 
     url = (url.indexOf('?') == -1) ? url + '?_' + dt.getTime() : url + '&_' + dt.getTime(); 
     if (url.indexOf('callback=') == -1) { 
      ajaxCallBack(url, function() { 
       if (this.readyState == 4 && this.status == 200) { 
        if (callback) { 
         if (params) { 
          callback(this.responseText, params); 
         } else { 
          callback(this.responseText); 
         } 
        } 
       } 
      }); 
     } else { 
      var NewScript = d.createElement("script"); 
      NewScript.type = "text/javascript"; 
      NewScript.src = url + '&_' + Math.random(); 
      d.getElementsByTagName('head')[0].appendChild(NewScript); 
     } 
    }, 
    ajaxCallBack = function (url, callback) { 
     var xmlhttp; 
     if (window.XMLHttpRequest) { 
      xmlhttp = new XMLHttpRequest(); 
     } else { 
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
     xmlhttp.onreadystatechange = callback; 
     xmlhttp.open("GET", url, true); 
     xmlhttp.send(); 
    } 

risposta

2

Ecco un example di come si può gestire un timeout:

var xmlHttp = new XMLHttpRequest(); 
xmlHttp.open("GET", "http://www.example.com", true); 

xmlHttp.onreadystatechange=function(){ 
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { 
     clearTimeout(xmlHttpTimeout); 
     alert(xmlHttp.responseText); 
    } 
} 
// Now that we're ready to handle the response, we can make the request 
xmlHttp.send(""); 
// Timeout to abort in 5 seconds 
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000); 
function ajaxTimeout(){ 
    xmlHttp.abort(); 
    alert("Request timed out"); 
} 

In IE8, è possibile aggiungere un gestore di eventi di timeout per l'oggetto XMLHttpRequest.

var xmlHttp = new XMLHttpRequest(); 
xmlHttp.ontimeout = function(){ 
    alert("request timed out"); 
} 

utilizzare un quadro di javascript per fare questo, però, non so il motivo per cui non lo si utilizza uno, ti piace il lavoro uneccesary? :)

+0

Grazie per il tuo aiuto ... ma non funziona nel mio codice come mostrato sopra ... puoi modificare il mio codice .... – Yogendra

+0

Dopo aver modificato un po ', ora funziona ... grazie ancora. – Yogendra

1

Forse la risposta a questa domanda sarà di aiuto. Timeout XMLHttpRequest

dal momento che da quello che ho capito è necessario impostare timeout per XMLHttpRequest, è possibile utilizzare xmlhttp.timeout = /*some number*/

+0

Grazie per il tuo aiuto ... ma non funziona nel mio codice come mostrato sopra ... puoi modificare il mio codice .... – Yogendra

2

Se si desidera aggiungere semplicemente il timeout, è possibile aggiungere nella prima funzione in tre punti:

 setTimeout(function() {callback(this.responseText, params)}, 1000) 

E la richiamata verrà eseguita circa 1 secondo dopo. Il secondo caso è la seconda chiamata di callback.

terzo posto che vorrei suggerire è quello di avvolgere questa funzione come sopra:

 ajaxCallBack(url, function() { 
      if (this.readyState == 4 && this.status == 200) { 
       if (callback) { 
        if (params) { 
         callback(this.responseText, params); 
        } else { 
         callback(this.responseText); 
        } 
       } 
      } 
     }); 

Di solito quando ottengo per testare la connessione internet Io invece ad aggiungere limitazione negli strumenti di Chrome per sviluppatori in questo modo:

enter image description here

Ecco il codice con primo approccio:

 AJAX = function (url, callback, params) { 
       var dt = new Date(); 
       url = (url.indexOf('?') == -1) ? url + '?_' + dt.getTime() : url + '&_' + dt.getTime(); 
       if (url.indexOf('callback=') == -1) { 
        ajaxCallBack(url, function() { 
         if (this.readyState == 4 && this.status == 200) { 
          if (callback) { 
           if (params) { 
            console.log(new Date()); 
            setTimeout(function() {callback(this.responseText, params)}, 2000); 
           } else { 
            console.error((new Date()).getSeconds()); 
            setTimeout(function() {callback(this.responseText)}, 2000); 
           } 
          } 
         } 
        }); 
       } else { 
        var NewScript = d.createElement("script"); 
        NewScript.type = "text/javascript"; 
        NewScript.src = url + '&_' + Math.random(); 
        d.getElementsByTagName('head')[0].appendChild(NewScript); 
       } 
      }, 
     ajaxCallBack = function (url, callback) { 
       var xmlhttp; 
       if (window.XMLHttpRequest) { 
        xmlhttp = new XMLHttpRequest(); 
       } else { 
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
       } 
       xmlhttp.onreadystatechange = callback; 
       xmlhttp.open("GET", url, true); 
       xmlhttp.send(); 
     } 

     AJAX('http://ip.jsontest.com/', function() {console.error((new Date()).getSeconds()); }); 
+0

Come si crea quella GIF ?! – Matt

+1

Gyazo, consente di creare facilmente gif brevi e schermate :) –

+0

Grazie per il tuo aiuto ... ma non funziona nel mio codice come mostrato sopra ... puoi modificare il mio codice .... – Yogendra

Problemi correlati