.post()处理错误 [英] error handling with .post()

查看:118
本文介绍了.post()处理错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须修改其他人编写的项目.因为代码是一团糟,所以我无法真正更改此$ .post()(或将其替换为$ .ajax()).我需要做的就是知道帖子是否返回其他内容,然后返回JSON并返回.

I have to modify a project written by someone else. Because the code is a mess I can't really change this $.post() (or replace it by $.ajax()). What I need to do, is to know if the post returns something else then JSON and return it.

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

我可以在console.log中看到发布回复.有没有简单的方法来检索它?

I can see the post response in the console.log. Is there a simple way to retrieve it?

推荐答案

有两种方法可以实现,但是如果您无法通过返回的JSON数据对象获得错误响应,则可以使用 $.ajaxSetup()为通过jQuery定义 all 所有ajax调用的默认值.即使$.post()方法本身并没有指定错误处理程序或回调,但$.ajaxSetup()方法仍将捕获任何ajax错误并执行您为其定义的功能.

There's a couple of ways to do it, but if you're not getting the error response available through the returned JSON data object, you can use $.ajaxSetup() to define defaults for all ajax calls through jQuery. Even though the $.post() method doesn't specify an error handler or callback in and of itself, the $.ajaxSetup() method will capture any ajax faults and execute the function you define for it.

或者,还有一个 $ .ajaxError()函数将执行相同的操作东西.

Alternatively, there is also an $.ajaxError() function that will do the same sort of thing.

请注意,如果您的JSON响应正确返回但带有服务器端错误代码,则此操作将无效.如果要捕获此类情况,最好使用 $ .ajaxComplete()方法

Note that this will not work if your JSON response is returned correctly but with a server-side error code. If you want to capture these sorts of cases, you might be best to look for them using the $.ajaxComplete() method

这篇关于.post()处理错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆