jQuery:处理getJSON()中的错误?

使用jQuery的getJSON时如何处理500错误?

有一些关于使用getJSON() 和 JSONP进行error handling的问题,但是我没有使用JSONP,只是普通的JSON。

另一个答案建议在调用getJSON()之前使用.ajaxSetup() getJSON() ,所以我尝试了这个:

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

但我发现警报总是会触发,即使结果格式正确。

有任何想法吗?

getJSON方法本身不返回错误,但您可以深入到作为回调中的参数返回的xhr对象。

getJSON方法是jQuery.ajax的简写函数。 使用jQuery.ajax可以轻松实现error handling:

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

如果您使用的是jquery 1.5或更高版本,则可以使用新方法.success(function),。error(function)和.complete(function)

来自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"); }); 

适合我的作品。 我希望这有帮助

你可以在jquery api getJSON上看到它: http : //api.jquery.com/jQuery.getJSON/

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

// jquery1.5 +当文本不是正确的json字符串或任何其他失败解决方案时,将触发失败回调

使用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); }); 

请执行以下操作。 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); } }