jQuery .fail和.done无法正常工作

时间:2015-05-19 09:50:37

标签: jquery ajax

我想在ajax调用失败时向用户显示一条消息。 方法1 在服务器成功响应和无法返回任何内容时都能正常工作。重构了方法2 中显示的代码后,在服务器出现故障的情况下,它无法正常工作:首先提醒'成功',然后'抱歉。服务器不可用。'显示。有什么想法吗?

方法1:

<!DOCTYPE html>

<html>
<head>
    <script src="../Scripts/jquery-1.8.2.js"></script>
    <title>Index</title>
</head>
<body>
    <script>
        var showInfo = function (msg) {
            alert(msg);
        }
    </script>
    <form id="register" method="post" action="">
        <input id="name" name="name" />
        <input id="join" type="submit" value="register" />
    </form>
    <script>
        $(function () {
            var $reg = $('#register');
            $reg.on('submit', function (e) {
                e.preventDefault();
                $.post('Home/AddUser', null)
                    // ----------------- Method 1 ---------------------
                    .done(
                        function () { alert('Success'); }
                        )
                    .fail(
                        function () { alert('Sorry. Server unavailable.');}
                        );
                    // --- End ---
            });
        });
    </script>
</body>
</html>

方法2:

<!DOCTYPE html>

<html>
<head>
    <script src="../Scripts/jquery-1.8.2.js"></script>
    <title>Index</title>
</head>
<body>
    <script>
        var showInfo = function (msg) {
            alert(msg);
        }
    </script>
    <form id="register" method="post" action="">
        <input id="name" name="name" />
        <input id="join" type="submit" value="register" />
        </form>
     <script>
        $(function () {
            var $reg = $('#register');
            $reg.on('submit', function (e) {
                e.preventDefault();
                $.post('Home/AddUser', null)
                    // ----------------- Method 2 ---------------------
                    .done(
                        showInfo('Success') 
                        )
                    .fail(
                        showInfo('Sorry. Server unavailable.')
                        );
                    // --- End ---
            });
        });
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:4)

您需要将函数引用作为param传递给done / fail方法,该方法将在ajax请求成功完成/失败后调用。

在你的情况下,你正在调用showInfo并将它返回的值作为参数传递给done / fail

$(function () {
    var $reg = $('#register');
    $reg.on('submit', function (e) {
        e.preventDefault();
        $.post('Home/AddUser', null)
        // ----------------- Method 2 ---------------------
        //need to pass a callback function which will call the alert
        .done(function () {
            showInfo('Success')
        })

            .fail(function () {
            showInfo('Sorry. Server unavailable.')
        });
        // --- End ---
    });
});