2

我倾向于在我的应用程序中对服务器端使用大量 jquery ajax 调用。

通常,当服务器端出现问题时,我会序列化错误消息并作为响应 (JSON) 发送。类似的东西

 { "ErrorMessage" : "Something went wrong: " + ex.message }

我想知道的是是否有任何方法可以使错误最终出现在 jquery ajaxerror回调中,而不是success.

有没有办法做到这一点?还是我应该坚持我处理错误的旧方法?如果您提供 PHP 或 ASP.NET + c# 示例并不重要,因为我对两者都很感兴趣。谢谢

4

2 回答 2

3

你可以让它们最终出现在error callbackjQuery 中。在 ASP.NET 中,您需要做的就是将custom errorsweb.config 中的部分更改为<customErrors mode="Off" /> 但是如果您走这条路,请确保将您的 Web 服务放在一个单独的文件夹中,以便您只为您的 Web 服务执行此操作在不关闭整个站点的情况下调用;例如:

<location Path="/Services"> <!--Your web service lives here -->
    <system.web>
        <customErrors mode="Off" />
    </system.web>
</location>

这样,在您的 Web 方法上抛出的任何异常都将在error callback在 jQuery 中处理。

您可以让异常传播而不将其缓存在您的 Web 方法中,或者您可以捕获它并重新抛出更“用户友好”的消息。

于 2012-05-14T19:34:32.160 回答
0

这可以Deferred在 jQuery 1.5+ 中使用对象。Ben Nadel 有一些例子,你可以看看这里http://www.bennadel.com/blog/2255-Using-jQuery-s-Pipe-Method-To-Change-Deferred-Resolution.htm和这里http ://www.bennadel.com/blog/2123-Using-Deferred-Objects-In-jQuery-1-5-To-Normalize-API-Responses.htm

这是其 JavaScript 代码的简化版本

var request = $.ajax({
    type: "post",
    url: "./web_service.cfm",
    dataType: "json"
});

request = request.pipe(

    // Filter the SUCCESS responses from the API.
    function (response) {

        // real success
        if (response.success) {
            return (response);
        }
        else {
            // The response is actually a FAIL even though it
            // came through as a success (200). Convert this
            // promise resolution to a FAIL.
            return (
                $.Deferred().reject(response)
            );
        }
    },

    // Filter the FAIL responses from the API.
    function (response) {
        return ({
            success: false,
            data: null,
            errors: ["Unexpected error: " + response.status + " " + response.statusText]
        });

    }

);


// Now that our API response has been filtered, let's attach
// our success and fail handlers to the promise resolution.
request.then(

    function (response) {
        console.log("Success!!!", response);
    },

    function (response) {
        console.log("Fail!!!", response);
    }

);
于 2012-05-14T19:44:19.013 回答