如果页面不存在,则加载特殊页面(404)

时间:2012-08-12 17:50:24

标签: javascript jquery load

我有一个小函数(下面),它接受一个参数来确定要加载的内容。有没有办法可以让它成为.load()有一个“其他”或后备如果它与404相关?

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

提前致谢:)

3 个答案:

答案 0 :(得分:4)

您可以指定加载完成时要执行的功能。

取自documentation

$("#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.statusTextNot 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();
        };
    });
}

请参阅DEMO

答案 1 :(得分: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);
  }
});

答案 2 :(得分:1)

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

$.ajaxSetup({
  statusCode: {
    404: function() {
      alert("page not found");
      //load the 404 page here
    }
  }
});
相关问题