read from data jquery json error-handling

from - json jquery html



jQuery: manejar errores en getJSON()? (5)

¿Cómo manejo 500 errores cuando uso el getJSON de jQuery?

Ha habido un par de preguntas sobre el manejo de errores con getJSON() and JSONP , pero no estoy trabajando con JSONP, solo JSON ordinario.

Otra respuesta sugiere usar .ajaxSetup() antes de llamar a getJSON() , así que intenté esto:

$.ajaxSetup({ "error":function() { alert(''Error!''); }}); $.getJSON(''/book_results/'', function(data) { # etc

Pero encuentro que la alerta siempre se dispara, incluso cuando el resultado está bien formado.

¿Algunas ideas?


El método getJSON no devuelve errores de forma nativa, pero podría sumergirse en el objeto xhr que se devuelve como un parámetro en la devolución de llamada.

El método getJSON es una función abreviada para jQuery.ajax . Usando jQuery.ajax puedes lograr fácilmente el manejo de errores:

$.ajax({ url: ''http://127.0.0.1/path/application.json'', dataType: ''json'', success: function( data ) { alert( "SUCCESS: " + data ); }, error: function( data ) { alert( "ERROR: " + data ); } });


Por favor haga lo siguiente. Código de Pseduo:

$.getJSON(''/path/to_your_url.do?dispatch=toggle&'' + new Date().getTime(), function(data, status, xhr){ if( xhr.status == 200 ) // all good and do your processing with ''data'' parameter( your response) else { //error - check out the values for only in chrome for ''console'' console.log(xhr.status); console.log(xhr.response); console.log(xhr.responseText) console.log(xhr.statusText); } }


Puedes verlo en jquery api getJSON: getJSON

$.getJSON(url).done(function(data){ $("#content").append(data.info); }) .fail(function(jqxhr){ alert(jqxhr.responseText); });

// jquery1.5 + la devolución de llamada fallida se activará cuando el texto no sea la cadena json correcta o cualquier otra solución fallida


Si está utilizando la versión 1.5 o superior de jquery, puede usar los nuevos métodos .success (function), .error (function) y .complete (function)

Ejemplo de http://api.jquery.com/jQuery.get/

// Assign handlers immediately after making the request, // and remember the jqxhr object for this request var jqxhr = $.get("example.php", function() { alert("success"); }) .success(function() { alert("second success"); }) .error(function() { alert("error"); }) .complete(function() { alert("complete"); }); // perform other work here ... // Set another completion function for the request above jqxhr.complete(function(){ alert("second complete"); });

Funciona perfecto para mi. espero que esto ayude


Usando jQuery 3.2.1:

$.getJSON(''/api/feed/update'', function (data) { console.log(data); }).catch(function (jqXHR, textStatus, errorThrown) { console.error(jqXHR); console.error(textStatus); console.error(errorThrown); });