如何在jQuery的Ajax响应接收错误? [英] How to receive error in jQuery AJAX response?

查看:149
本文介绍了如何在jQuery的Ajax响应接收错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery $。阿贾克斯()函数PHP页面上执行数据库插入操作。因此,在成功的话会做常规操作,但我想如果更新操作失败的Ajax调用接收错误。

I am using jQuery $.ajax() function to perform a database insert operation on a php page. So, on success it will do the regular operation but I want the ajax call to receive error if the update operation fails.

所以,它应该是:

  1. $阿贾克斯 - >调用PHP函数
  2. 在接收成功的记录插入成功
  3. 在unsuccessfull插入接收错误

所以,我应该做一回虚假的;从我的PHP函数?我认为,$。阿贾克斯()成功或错误的决定,如果AJAX调用成功与否。所以,我想就算我返回false;从我的PHP函数它仍然被认为是成功的Ajax调用。右

So, should I do a return false; from my php function? I think the $.ajax() success or error depends if the AJAX call was successful or not. So, I think even if I return false; from my php function it will still be considered a "success" for the ajax call. Right

推荐答案

您可以在您的服务器响应(或使用JSON)有人建议返回错误信息。但我不喜欢它太多,因为这种污染返回的数据。

You could return the error message in your server response (or using JSON) as someone suggested. But I don't like it too much because this pollutes the data returned.

我喜欢另一种方式我一直在使用最近所,其中包括创建一个自定义的HTTP头,如果有一个错误通知。

I like another way I've been using recently, which involves creating a custom HTTP header to inform if there was an error.

PHP code:

if($there_was_error){
   header("DB_SUCCESS: 0"); //Sends a custom header
}else{
   header("DB_SUCCESS: 1");
}

jQuery的code:

jQuery code:

$.ajax({
  ...
  success: function(data, status, xhr){
     //You can use your 'data' var as always
     if(xhr.getResponseHeader("DB_SUCCESS") == 1){
        alert("Save successful");
        //Your regular sutff
     }else{
        alert("Save failed");
     }         
  }
  ...
})

正如你所看到的,我们创建了一个自定义HTTP标头,叫 DB_SUCCESS 来作为元数据,因此我们可以将其指定服务器端(PHP)和阅读与客户端(JavaScript)知道,如果有一个错误。

As you can see, we created a custom HTTP header, called DB_SUCCESS to be used as metadata, so we can assign it server-side (php) and read it with client-side (javascript) to know if there was an error.

希望这有助于。干杯

这篇关于如何在jQuery的Ajax响应接收错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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