简体   繁体   English

如何正确处理jquery ajax成功和失败

[英]how to handle jquery ajax success and failure correctly

So I have a jquery ajax call like so: 所以我有一个像这样的jQuery ajax调用:

$.ajax({
     url: 'delete.php', 
     data : {
          'prd_id': <prd-id-number>
     },
     success: function(data) {
          //show success here
     },
     error : function(error) {
          //show error here
     }
 });

My doubt is about the success and error handlers . 我对successerror handlers疑问。 Is the error handler only used for "ajax level" error? 错误处理程序仅用于"ajax level"错误吗? I mean - my application can have its own error, for.eg the passed product id does not exist or is incorrect. 我的意思是-我的应用程序可能会有自己的错误,例如,传递的产品ID不存在或不正确。 Now, currently what I am passing a message back, which goes into success() then I have to do some internal logic to see if the message is an application error or truly success - and based on that I show the message. 现在,当前,我正在传递回一条消息,并将其传递给success()然后我必须执行一些内部逻辑,以查看该消息是应用程序错误还是真正的成功-并在此基础上显示该消息。

is there any way I can send the message to error() - is that the proper way to trap and handle ajax errors? 有什么方法可以将消息发送给error() -是捕获和处理ajax错误的正确方法吗?

Ajax error can be triggered several different ways. Ajax错误可以通过几种不同的方式触发。 The most common ones are , http status not being 200, timeout and data parsing errors such as incorrectly formatted json. 最常见的错误是,http状态不为200,超时和数据解析错误(例如json格式错误)。

You can trigger the error yourself from server by returning an http response code header. 您可以通过返回http响应代码标头自己从服务器触发错误。

For example assume you have an API that looks up users by ID and you send an invalid ID. 例如,假设您有一个按ID查找用户的API,并且发送了无效的ID。 You can return a 404 response code header with data included that can be used in your app from within the error callback. 您可以返回404响应代码标头,其中包含可在错误回调中的应用中使用的数据。

This allows you to set up the application code to handle both types of errors using the error callback 这使您可以使用错误回调来设置应用程序代码以处理两种类型的错误

Well i think you need to recall some concepts. 好吧,我认为您需要回顾一些概念。

ajax success and error handlers are called depending upon the success or failure of the axaj call send. 根据axaj调用发送的成功或失败,将调用ajax成功和错误处理程序。

success handler is called whenever the ajax call has successfully completed while error handler is called whenever the ajax call could not be completed due to any sort of error. 只要ajax调用成功完成,就调用成功处理程序,而由于某种错误而无法完成ajax调用时,则调用错误处理程序。

For your case you will have to manipulate the success handler and show the required message. 对于您的情况,您将必须操纵成功处理程序并显示所需的消息。

There is no way to call error handler when your ajax call has been successfully completed. 成功完成ajax调用后,将无法调用错误处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM