让$ .ajax失败

时间:2015-07-27 08:47:42

标签: php jquery ajax

这是一个奇怪的问题,但是,我想让$ .ajax无法检查我的失败触发器,我有这个jQuery代码:

$(document).ready(function () {
    $("#trigger").on("click", function () {
        $.ajax({
            url: "text.php",
            success: function (data) {
                $(".log").html(data.slice(0, 1000));
                //alert("Load has been performed");
            },
            fail: function () {
                $(".msg").html("Something went wrong...");
            }
        });
    });
});

我正在调用这个PHP代码:

<?php
function foo()
{
    return "bar";
}

print foo();

return false;
?>

并希望确保fail: ...正常运行。我该怎么做?

修改

我已将text.php修改为:

<?php
throw new LogicException("Failed");

此外:

<?php
header("HTTP://this.does.not.exist");

但即使失败,这仍然显示在$(".log")区域。

注意到我使用了失败函数错误,现在将我的jQuery修改为:

$(document).ready(function () {
    $("#trigger").on("click", function () {
        $.ajax({
            url: "text.php"
        }).done(function (data) {
            $(".log").html(data.slice(0, 1000));
        }).fail(function () {
            $(".msg").html("Something went wrong...");
        }).always(function () {
            alert("One way or another, we did it!");
        });
    });
});

如果它有帮助,我将这些脚本用于jQuery库:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

2 个答案:

答案 0 :(得分:3)

您可以发送一个返回错误的标头。

例如:

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

当然,您的脚本会产生致命错误; - )

答案 1 :(得分:2)

两个建议:

  1. .fail回拨电话改为.error

  2. 尝试从服务器返回错误状态代码,如jeroen建议,

    header("not-real.php", true, 404);