2013-06-17 10 views
7

Mi chiedo, qual è il modo migliore per gestire i timeout con jQuery.ajax(). Questa è la mia soluzione al momento: se si verifica un timeout, la pagina verrà ricaricata e lo script avrà un'altra possibilità di caricare i dati all'interno del tempo previsto.jQuery.ajax() - Come gestire meglio i timeout?

: se "get_json.php" (esempio sotto) non è realmente disponibile, diventerà un ciclo di ricarica infinito. Possibile soluzione: aggiungere un contatore e annullare dopo $ x ricariche.

Domanda 1: Come gestire l'errore di timeout migliore?

Domanda 2: Qual è il tuo periodo di tempo consigliato per un timeout e perché?

Codice:

$.ajax({ 
    type: "POST", 
    url: "get_json.php", 
    timeout: 500, 
    dataType: "json", 
    success: function(json) { 
     alert("JSON loaded: " + json); 
    }, 
    error: function(request, status, err) { 
     if (status == "timeout") { 
      // timeout -> reload the page and try again 
      console.log("timeout"); 
      window.location.reload(); 
     } else { 
      // another error occured 
      alert("error: " + request + status + err); 
     } 
    } 
}); 

Grazie in anticipo!

+5

Perché ricaricare l'intera pagina anziché riprovare semplicemente la chiamata Ajax? – JJJ

+1

@Juhana: intendi $ .ajax (questo); ? –

+2

Beh, sì, per esempio. – JJJ

risposta

4

È possibile farlo in un altro modo, è possibile cancellare prima l'intervallo quando si verifica un timeout. Se usi questa funzione clearInterval() allora non dovrai ricaricare la pagina. Si fermerà automaticamente.

function ajax_call(){ 
$.ajax({ 
     type: "POST", 
     url: "get_json.php", 
     timeout: 500, 
     dataType: "json", 
     success: function(json) { 
      alert("JSON loaded: " + json); 
     }, 
     error: function(request, status, err) { 
      if (status == "timeout") { 
       // timeout -> reload the page and try again 
      clearInterval(ajax_call); 
       window.location.reload(); //make it comment if you don't want to reload page 
      } else { 
       // another error occured 
       alert("error: " + request + status + err); 
      } 
     } 
    }); 
} 

setInterval(ajax_call,timeout_duration); 
Problemi correlati