2010-06-18 14 views
9

Abbiamo scritto un'API server RESTful. Per qualsiasi ragione, abbiamo preso la decisione che per i DELETE, vorremmo restituire un codice di stato 204 (nessun contenuto), con una risposta vuota. Sto cercando di chiamare questo da jQuery, passando in un gestore di successo e impostando il verbo da eliminare:

jQuery.ajax({ 
    type:'DELETE', 
    url: url, 
    success: callback, 
}); 

il server restituisce un 204, ma il gestore successo non è mai chiamato. C'è un modo per configurare jQuery per consentire a 204s di attivare il gestore di successo?

risposta

11

204 dovrebbero essere trattati come il successo. Quale versione di jQuery stai usando? Ho fatto un paio di test e tutti i 200 codici di stato della gamma sono andati al gestore del successo. La fonte per jQuery 1.4.2 conferma:

// Determines if an XMLHttpRequest was successful or not 
httpSuccess: function(xhr) { 
    try { 
     // IE error sometimes returns 1223 when 
     // it should be 204 so treat it as success, see #1450 
     return !xhr.status && location.protocol === "file:" || 
      // Opera returns 0 when status is 304 
      (xhr.status >= 200 && xhr.status < 300) || 
      xhr.status === 304 || xhr.status === 1223 || xhr.status === 0; 
    } catch(e) {} 

    return false; 
}, 
+0

Ok, ora sono confuso. Ci sto provando di nuovo, e sembra che funzioni. Sembra che devo aver fatto qualcos'altro in modo errato. Grazie! – Bennidhamma

3
jQuery.ajax({ 
    ... 
    error: function(xhr, errorText) { 
     if(xhr.status==204) successCallback(null, errorText, xhr); 
     ... 
    }, 
    ... 
}); 

brutto ... ma potrebbe aiutare

+0

Grazie sje397, ha senso. Pensi che sia l'unico modo? – Bennidhamma

9

Ho avuto un problema simliar perché il mio script è stato anche inviando il "Content-Type" come "application/json". Mentre la richiesta è riuscita, non è stato possibile JSON.parse una stringa vuota.

2

E 'tecnicamente un problema sul server
Come Paolo ha detto, un un 204 risposta vuota con un server di tipo di contenuto di JSON è trattata da jQuery come un errore.

È possibile aggirare in jQuery ignorando manualmente dataType su "testo".

$.ajax({ 
    url: url, 
    dataType:'text', 
    success:(data){ 
     //I will now fire on 204 status with empty content 
     //I have beaten the machine. 
    } 
}); 
2

Questo è modo alternativo per richiamata in caso di successo ... penso che lavorerà per voi.

$.ajax({ 
    url: url, 
    dataType:'text', 
    statusCode: { 
       204: function (data) { 
        logic here 
       } 
}); 
Problemi correlati