jQuery 使用 .post() 处理错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2697719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:05:57  来源:igfitidea点击:

error handling with .post()

jquery

提问by meo

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()(或将其替换为 $.ajax())。我需要做的是知道帖子是否返回其他内容然后返回 JSON 并返回它。

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

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

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

采纳答案by Phil.Wheeler

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 allajax 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.

有几种方法可以做到这一点,但是如果您没有通过返回的 JSON 数据对象获得可用的错误响应,您可以使用$.ajaxSetup()通过 jQuery为所有ajax 调用定义默认值。即使该$.post()方法本身没有指定错误处理程序或回调,该$.ajaxSetup()方法也会捕获任何 ajax 错误并执行您为其定义的函数。

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

或者,还有一个$.ajaxError()函数可以做同样的事情。

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

请注意,如果您的 JSON 响应正确返回但带有服务器端错误代码,这将不起作用。如果您想捕获这些类型的情况,最好使用$.ajaxComplete()方法查找它们

回答by hyprnick

Define the error callback immediately after the post. Note the semi-colon placement only at the end.

发布后立即定义错误回调。请注意分号位置仅在末尾。

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

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

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

For older versions of jQuery (pre-1.8)Use .errorinstead with the same syntax.

对于旧版本的 jQuery(1.8 之前),请使用.error代替相同的语法。

回答by Victor

You can use $.ajax()($.postis a shortcut that ends up calling it anyway), and define the error callback.

您可以使用$.ajax()($.post是最终调用它的快捷方式),并定义错误回调。

Or, if you really do not want to do that, call

或者,如果您真的不想这样做,请致电

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

before that $.post

在那之前 $.post