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

AP2*_*257 23 error-handling jquery json

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

有关JSONP getJSON() JSONP的错误处理有几个问题,但我不使用JSONP,只是普通的JSON.

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

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

但我发现警报总是会触发,即使结果是格式良好的.

有任何想法吗?

hal*_*.am 27

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

getJSON方法是一种速记函数jQuery.ajax.使用jQuery.ajax您可以轻松实现错误处理:

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


bib*_*tha 11

如果您使用的是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"); });
Run Code Online (Sandbox Code Playgroud)

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


lee*_*lee 8

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

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

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