【问题标题】:AJAX call triggers success callback even if server script exists with error即使服务器脚本存在错误,AJAX 调用也会触发成功回调
【发布时间】:2014-12-19 06:14:13
【问题描述】:

即使下面的 PHP 代码因错误退出,AJAX 代码中的 success 回调仍然会被触发。这是为什么呢?

JavaScript 代码:

$.ajax({
            type: "POST",
            url: xxxx,
            data: {info:data},
            success: function(result){
               //code here
            },
            error:function(msg)
            {
                alert('add data error,please add again');
            }
        });

php代码:

        if(is_wrong) //data is error
        {
            exit("the data is not right,please add again");
        }

【问题讨论】:

  • 你的 PHP 代码是什么?
  • 如果ajax请求成功,jquery ajax中的成功回调总是会被触发。这与您从 php 文件中获得或未获得的响应无关。如果 request 有错误,那么错误回调函数才会被执行。

标签: php ajax callback


【解决方案1】:

在客户端和服务器之间进行通信时,有多种方法可以处理错误或成功。

1.带有 HTTP 状态码

将调用其中一个$.ajax() 回调(successerror),具体取决于服务器返回的HTTP status code。 “正常”成功代码是 200 OK。当您使用 PHP 脚本发送输出时,如果一切顺利,您生成的内容将使用代码 200 发送。

当您在此处调用exit() 时就是这种情况。从您的客户端 JavaScript 代码的角度来看,由于它收到状态代码 200 OK,它将调用 success 回调。如果您希望执行错误回调,则必须在 PHP 代码中发送自定义标头,发送任何其他输出之前。

您可以使用header function 实现此目的。例如,以下代码可用于生成“404 Not Found”状态:

header("HTTP/1.0 404 Not Found");

在这里,您需要找到另一个更符合您的代码的 HTTP 代码。我不认为这种方法是最好的解决方案,因为 HTTP 状态代码是服务器状态代码,即不用于反映应用程序错误代码。

2。用你自己的约定

处理应用程序错误代码的另一种方法是处理来自success() 处理程序的所有内容。您不会从 PHP 中设置错误代码,而是建立一个约定来告诉您何时出现应用程序错误或正常情况。您仍将保留 error() 回调,以便您可以处理各种 HTTP 错误(即,如果您与服务器的连接中断)。

例如,如果您将数据以 JSON 格式从服务器发送到客户端,则可以从您的 php 发送:

if(is_right) //data is ok
{
    $response = array(
        'data' => $someData, // any data you might want to send back to the client
    );
}
if(is_wrong) //data is error
{
    $response = array(
        'error' => "the data is not right,please add again"
    );
}
// Called in both cases
exit(json_encode($response));

在您的客户端代码中,您将拥有:

...,
success: function(result) {
    if(data.error !== undefined) {
        // do something if your server sent an error
        console.log(data.error);
    }
    else {
        var data = result.data;
        // do something with the data
    }
},
...

【讨论】:

  • 欣赏。这正是我在我的应用程序中使用的。
猜你喜欢
  • 2021-07-24
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
  • 2013-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多