Ecco il mio codice:Come rendere jQuery analizza la mia risposta di errore rappresentata come un json valido?
$.ajax({
url: "/api/invoice/" + newInvoice._id,
type: 'PUT',
data: JSON.stringify(newInvoice),
dataType: 'json',
contentType: "application/json; charset=utf-8"
})
.success(function() {
$('#statusLine').text('Successfully submitted invoice {0}. Click here to dismiss.'.format(newInvoice._id));
})
.error(function (err) {
alert(err);
});
La richiesta:
PUT http://localhost:8000/api/invoice/16211 HTTP/1.1
Host: localhost:8000
Connection: keep-alive
Content-Length: 770
Origin: http://localhost:8000
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11
Content-Type: application/json; charset=UTF-8
Accept: application/json, text/javascript, */*; q=0.01
Referer: http://localhost:8000/invoice.html?id=16211
Accept-Encoding: gzip,deflate,sdch
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
{"items":[{"id":...
Il corpo della richiesta è in realtà un JSON valida, ho appena troncato per brevità.
La risposta:
HTTP/1.1 409 Conflict
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 1386
ETag: 250542419
Connection: keep-alive
{
"msg": "Cannot update the invoice #16211, because it has already been updated by someone else.",
"invoice": {
"items": [
{...
nuovo, la risposta è un json completamente valido, troncato per brevità.
Come previsto, il gestore error
viene richiamato con l'oggetto err
. Tuttavia, come posso impadronirmi del suono analizzato? Certo, potrei verificare che il tipo di contenuto della risposta sia json e quindi analizzare lo err.responseText
da solo, ma non è quello che jQuery ajax dovrebbe fare per me? Voglio dire, lo fa per le mie query $.get
quando ottengo gli oggetti dal server.
Cosa mi manca?
EDIT
Si tratta di una correzione al https://stackoverflow.com/a/12310751/80002:
fare la richiesta:
var ajax = $.ajax(...
L'elaborazione della risposta di errore:
var res, ct = ajax.getResponseHeader("content-type") || '';
if (ct.indexOf('json') > -1) {
res = $.parseJSON(err.responseText);
// process the response here
}
+1 Vorrei poter contrassegnare sia le vostre sia le risposte di Joel come una risposta. – mark