2011-01-14 10 views
13

Come si rileva Errore server o pagina 404 non trovata, quando si utilizza $ .get o $ .post?

Ad esempio:

$.post("/myhandler", { value: 1 }, function(data) { 
    alert(data); 
}); 

che farà assolutamente nulla se non v'è un errore di server loading "/ MyHandler", o se non viene trovato.

Come si avvisa l'utente in caso di errore?

risposta

20

uso error gestore on $.ajax()

$.ajax({ 
    url: "/myhandler", 
    data: {value: 1}, 
    type: 'post', 
    error: function(XMLHttpRequest, textStatus, errorThrown){ 
     alert('status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText); 
    }, 
    success: function(data){} 
}); 

demo

+6

Così è questo non è possibile con $ .get ? –

+0

Idem, può qualcosa di simile essere fatto per load()? –

+1

@OldGeezer puoi fare qualcosa di simile, leggi questo http://api.jquery.com/load/ – Reigel

5

Le altre risposte sono bello e tutto, ma non c'è soluzioni alternative, vale a dire .ajaxSetup, .ajaxError e altri gestori di eventi Ajax (assegno la pagina del documento ajaxSetup per maggiori informazioni sul resto).

Ad esempio, con .ajaxError è possibile impostare un gestore globale di tutti i tuoi errori Ajax da .post, .get, .getJSON e .ajax per uno specifico insieme di elementi.

$(selector).ajaxError(function(event, xhr, ajaxOptions, errorThrown) { 
    // handle ajax error here 
}); 
33

si potrebbe fare

$.post("/myhandler", { value: 1 }, function(data) { 
    alert(data); 
}).fail(function(){ 
    // Handle error here 
}); 

fail saranno chiamati se c'è un errore

+5

+1 per la funzione fail. fa il lavoro! Si può usare in questo modo: .fail (function (e) { \t se (e.status == 404) {// ... \t} \t else {// ... \t } }); – sladda

+0

Il codice precedente con .error() non stava rilevando nulla. Semplicemente passando a fail() ha fatto il trucco. –

1

Prova utilizzando $.ajaxSetup(), stausCode opzione

$.ajaxSetup({ 
    statusCode : { 
    // called on `$.get()` , `$.post()`, `$.ajax()` 
    // when response status code is `404` 
    404 : function (jqxhr, textStatus, errorThrown) { 
      console.log(textStatus, errorThrown); 
      } 
    } 
}); 

// $.get("/path/to/url/"); 
// $.post("/path/to/url/"); 
// $.ajax({url:"/path/to/url/"}) 
Problemi correlati