jquery 错误处理.post()

llycmphe  于 12个月前  发布在  jQuery
关注(0)|答案(4)|浏览(149)

我得修改别人写的项目。因为代码很乱,我不能真正更改这个$.post()(或者用$. AJAX ()替换它)。我需要做的是知道post是否返回JSON之外的其他内容并返回它。

$.post('balbal.html', json, function(data) { ... my coude ... }, 'json')

我可以在console.log中看到帖子响应。有没有一个简单的方法来恢复它?

dpiehjr4

dpiehjr41#

在post之后立即定义错误回调。请注意分号仅在结尾处放置。

$.post('balbal.html', json, function(data) {
    // ... my code ...
})
.fail(function(response) {
    alert('Error: ' + response.responseText);
});

http://api.jquery.com/deferred.fail/

**对于旧版本的jQuery(pre-1.8)**使用.error代替相同的语法。

ulmd4ohb

ulmd4ohb2#

有几种方法可以做到这一点,但是如果您没有通过返回的JSON数据对象获得可用的错误响应,您可以使用$.ajaxSetup()通过jQuery为 *all AJAX 调用定义默认值。即使$.post()方法本身没有指定错误处理程序或回调,$.ajaxSetup()方法也会捕获任何 AJAX 错误并执行您为其定义的函数。
或者,还有一个$.ajaxError()函数可以做同样的事情。
请注意,如果您的JSON响应正确返回,但带有服务器端错误代码,则这将不起作用。如果希望捕获这类情况,最好使用$.ajaxComplete()方法查找它们

u3r8eeie

u3r8eeie3#

你可以这样做:

// Assign handlers immediately after making the request, and remember the jqxhr object for this request.
var jqxhr = $.post("example.php", function() {
  alert("success");
  })
  .done(function() {
    alert("second success");
  })
  .fail(function() {
    alert("error");
  })
  .always(function() {
    alert("finished");
  });
});
 
// Your other code here.
 
// Set another completion function for the request above.
jqxhr.always(function() {
  alert( "second finished" );
});

$.post文档https://api.jquery.com/jquery.post/

ijnw1ujt

ijnw1ujt4#

您可以使用$.ajax()$.post是一个快捷方式,最终无论如何都会调用它),并定义错误回调。
或者,如果你真的不想这样做,打电话

$.ajaxError(function(){
   //error handler
})

在此之前$.post

相关问题