如果页面不存在,则加载特殊页面(404) [英] Load special page if page doesn't exist (404)
问题描述
我有一个小函数(如下),该函数带有一个参数来确定要加载的内容.我是否可以通过某种方式使.load()遇到"404"错误或回退?
I have a small function (below) that takes a parameter to determine what to load. Is there a way I can make it so that the .load() kind of has an "else" or a fallback if it ecounters a 404?
function start(page,last){
$("#area").load("pages/"+page+".inc.php");
loading();
}
先谢谢您了:)
推荐答案
您可以指定加载完成后要执行的函数.
You can specify a function to be executed when the load completes.
来自 文档 :
$("#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);
}
});
使用您的代码,它看起来类似于:
Using your code it would look similar to this:
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.
You can check the linked documentation for more details on possible return values and errors. In fact the demo on the bottom of the documentation shows dealing with a 404.
xhr.status
包含错误号404
,xhr.statusText
为Not Found
.
这意味着您可以检查特定的数字:
This would mean you can check for the specific number:
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();
};
});
}
请参见 演示
这篇关于如果页面不存在,则加载特殊页面(404)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!