如何根据服务器响应触发jquery.ajax()错误回调,而不是HTTP 500?

问题描述 投票:40回答:6

通过使用jquery ajax函数,我可以做类似的事情:

$.ajax({

  url: url,
  type: 'GET',
  async: true,
  dataType: 'json',
  data: data,

 success: function(data) {

     //Handle server response here

  },

 error: function(xhr, status, error){

    //Handle failure here

 }

});

根据以上代码,我有两个问题要问:

  1. 什么时候调用jquery.ajax()error回调?
  2. 如果服务器使用字符串消息“有错误”向我回复json对象怎么办?这意味着请求仍然成功发送,但我得到了服务器响应{message: "There is an error"}

我想无论服务器响应什么字符串值,如果客户端得到服务器的响应,无论如何都会触发jquery.ajax()success回调。

我想问一下服务器是否专门向我返回一个字符串值为{message: 'There is an error'}的JSON对象,服务器可以做一些事情,以便可以在jquery.ajax()error回调而不是success回调中处理此响应吗?

javascript ajax spring jquery
6个回答
31
投票

当服务器的响应不符合您的预期时,将执行错误回调。例如,在这种情况下,它:

  • 已收到HTTP 404/500或任何其他HTTP错误消息
  • 收到了不正确类型的数据(即您预期JSON,您已收到其他内容)。

在您的情况下,数据是正确的(这是一个JSON消息)。如果要根据接收数据的值手动触发错误回调,则可以非常简单地完成。只需将错误的匿名回调更改为命名函数即可。

function handleError(xhr, status, error){

    //Handle failure here

 }

$.ajax({

  url: url,
  type: 'GET',
  async: true,
  dataType: 'json',
  data: data,

 success: function(data) {
     if (whatever) {
         handleError(xhr, status, ''); // manually trigger callback
     }
     //Handle server response here

  },

 error: handleError
});

26
投票

我们假设服务器正在发送JSON,如果请求成功,我们将得到如下内容:

{
    success: true,
    data: {
        name: 'Foo'
    }
}

......并且失败了:

{
    success: false,
    error: 'Something bad happened.'
}

然后我们只需用$.Deferred过滤响应:

$.get('http://localhost/api').then(function(res) {
    var filter = $.Deferred();

    if (res.success) {
        filter.resolve(res.data);
    } else {
        filter.reject(res.error);
    }

    return filter.promise();
}).done(function(data) {
    console.log('Name:',  data.name); // Outputs: Foo
}).fail(function(error) {
    console.log('Error:', error); // Outputs: Something bad happened.
})

3
投票

错误回调是为了无法成功完成Ajax往返,而不是基于您的服务器逻辑。您有责任在成功回调中检查您认为成功响应的内容。即添加一个IF条件,检查消息是否为“出错”。并在那里包含您的错误逻辑,否则执行成功逻辑。

执行您要求的方法是让服务器在出现错误时返回404标头,然后由错误回调处理。这种方法的问题在于,如果存在实际错误,您将隐藏,并且您将无法使用它传递其他数据。


2
投票

最简单的事情就是像这样重组:

function handleAjaxError function(xhr, status, error) {
    //Handle failure here
}

$.ajax({
  url: url,
  type: 'GET',
  async: true,
  dataType: 'json',
  data: data,

  success: function(data) {

     //Handle server response here
    if (data.message == 'There is an error')
    {
        handleAjaxError();
        return;
    }

    //... all is good....

  },
  error: handleAjaxError
});

0
投票

一个简单的方法是只使用jQuery always()函数进行回调,然后如果你想手动创建错误就可以利用Duck Typing!

例如:

$.get(url, {"data": data}).always(function(result)
{
    if (typeof result.status !== "undefined" && result.status !== 200) // Status code 200 represents Success/OK
    {
        //handle error
        error = "Your error was " + result.status + " " + result.statusText;
    }
    else
    {
        //success
    }
});

如果存在自然标头错误(例如404 Not Found),则始终会运行错误部分。如果要手动返回错误,可以模拟通常传递错误的XHR对象(例如在PHP中):

public function ServerSideAjaxResponse($data)
{
    if (!$data)
    {
        $response["status"] = 1001; //Make up your own error codes! Yippee! Fun!
        $response["statusText"] = "Error! You forgot to send the data!";
        echo json_encode($return);
        return;
    }
}

0
投票

这个原始问题是在几年前发布的,也许现在有更好的方法来处理这个问题。这是一个处理多种类型错误的建议,包括OP的问题。

Input type (error) example #1

function handleError (type){
type = type || "Connection Issue";
 var value = "Error occurred: " + type;
 alert(value);
}

function checkIfError(response){
    if (response == "DB_ERROR") {
        handleError("Server error");
        throw new Error("JS died"); // optional, keep from running additional script
     }
}

var example = {

    success: function (response) {
        checkIfError(response); // check data if error msg
        // do stuff when proper data sent
        alert(response);

    }, error: handleError // connection error, call error msg
};

test1 = example['error']();

Input type (success:error) example #2

function handleError (type){
type = type || "Connection Issue";
 var value = "Error occurred: " + type;
 alert(value);
}

function checkIfError(response){
    if (response == "DB_ERROR") {
        handleError("Server error");
        throw new Error("JS died"); // optional, keep from running additional script
     }
}

var example = {

    success: function (response) {
        checkIfError(response); // check data if error msg
        // do stuff when proper data sent
        alert(response);

    }, error: handleError // connection error, call error msg
};


test2 = example['success']("DB_ERROR");

Input type (success) example #3

function handleError (type){
type = type || "Connection Issue";
 var value = "Error occurred: " + type;
 alert(value);
}

function checkIfError(response){
    if (response == "DB_ERROR") {
        handleError("Server error");
        throw new Error("JS died"); // optional, keep from running additional script
     }
}

var example = {

    success: function (response) {
        checkIfError(response); // check data if error msg
        // do stuff when proper data sent
        alert(response);

    }, error: handleError // connection error, call error msg
};


test3 = example['success']("Proper Response");

通过使用函数,如果脚本中有多个调用,则可以简化更改。

让你的PHP(或任何服务器端代码)返回“DB_ERROR”(或任何你想要的)的响应来触发错误;允许您根据错误执行不同的操作。

© www.soinside.com 2019 - 2024. All rights reserved.