使$.ajax请求失败

5

这是一个有些奇怪的问题,但我想让$.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")区域。

注意到我使用了错误的fail函数,现在我已经更正了我的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>

你试过发送500服务器错误代码头吗?(而不是4xx客户端错误)? - STT LCU
1
@STTLCU,是的,它没有起作用。 - Can O' Spam
聊天功能由@pingul提供,在此处可用。 - Can O' Spam
@SamSwift:请将解决方案作为答案添加到问题中,而不是附加到问题后面。 - Matt
@Matt,我只是想在这里感谢Pingul为我提供的大量帮助。 - Can O' Spam
@SamSwift:在Stack Overflow上给别人信用的方式是接受他们的答案...你已经做到了,并且点赞它 :)。 - Matt
2个回答

3
你可以发送一个返回错误的头部信息。
例如:
header("HTTP/1.0 404 Not Found");

当然,您也可以让您的脚本生成致命错误;-)

1
为什么我从来没有想到过那个! - Can O' Spam
2
@SamSwift 使用error回调函数和使用fail回调函数有什么区别吗? - pingul
@pingul,你说的回调函数是什么意思?(不是要表现得很蠢,只是我做这个还不太久!) - Can O' Spam
@SamSwift pingul 是正确的,似乎没有 fail 属性,只有返回对象上的 fail() 方法。因此,您需要使用 error: function() {} - jeroen
@pingul,很遗憾,它没有起作用。我正在使用 jQuery Windows 8.1 商店应用作为参考,它说要使用 fail 函数来捕获错误... - Can O' Spam
显示剩余3条评论

2
两个建议:
  1. Change the .fail callback call to .error and

  2. Try it by returning an error status code from your server like jeroen suggested,

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接