1

我有一个小函数(如下),它需要一个参数来确定要加载的内容。有没有办法让 .load() 遇到 404 时有一个“else”或一个后备?

function start(page,last){
$("#area").load("pages/"+page+".inc.php");
loading();
}

提前致谢 :)

4

3 回答 3

4

您可以指定加载完成时要执行的函数。

取自文档

$("#success").load("/not-here.php", function(response, status, xhr) {
  if (status == "error") {
    var msg = "Sorry but there was an error: ";
    $("#error").html(msg + xhr.status + " " + xhr.statusText);
  }
});

使用您的代码,它看起来类似于:

function start(page,last){
    $("#area").load("pages/"+page+".inc.php", function(response, status, xhr) {
        if (status == "error") {
            // don't load as an error occured,...do something else...
        }
        else{
            loading();
        };
    });
}

您可以查看链接文档以获取有关可能的返回值和错误的更多详细信息。事实上,文档底部的演示显示了处理 404。

xhr.status样本中包含错误号404xhr.statusTextis Not Found

这意味着您可以检查特定数字:

function start(page,last){
    $("#area").load("pages/"+page+".inc.php", function(response, status, xhr) {
        if (status == "error" && xhr.status == ""404) {
            // a 404 occurred...
        }
        else{
            loading();
        };
    });
}

演示

于 2012-08-12T17:52:10.647 回答
2

.load()有 responseText 和 textStatus 参数告诉你它什么时候成功,所以你可以用它来检查它是否失败。成功的响应将生成“成功”或“未修改”,而错误生成“错误”。

$("#success").load("/not-here.php", function(response, status, xhr) {
  if (status == "error") {
    var msg = "Sorry but there was an error: ";
    $("#error").html(msg + xhr.status + " " + xhr.statusText);
  }
});
于 2012-08-12T17:52:28.183 回答
1

ajaxSetup您可以定义状态代码,如

$.ajaxSetup({
  statusCode: {
    404: function() {
      alert("page not found");
      //load the 404 page here
    }
  }
});
于 2012-08-12T17:52:39.717 回答