何をロードするかを決定するためにパラメータを取る小さな関数(以下)があります。404 に遭遇した場合、.load() の種類が「else」またはフォールバックを持つようにする方法はありますか?
function start(page,last){
$("#area").load("pages/"+page+".inc.php");
loading();
}
前もって感謝します :)
何をロードするかを決定するためにパラメータを取る小さな関数(以下)があります。404 に遭遇した場合、.load() の種類が「else」またはフォールバックを持つようにする方法はありますか?
function start(page,last){
$("#area").load("pages/"+page+".inc.php");
loading();
}
前もって感謝します :)
ロード完了時に実行する関数を指定できます。
ドキュメントから取得:
$("#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
サンプルには、エラー番号404
とxhr.statusText
is が含まれています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();
};
});
}
デモを見る
.load()
成功した場合に通知する responseText および textStatus パラメーターがあるため、それを使用して失敗したかどうかを確認できます。成功応答は「success」または「notmodified」を生成し、エラーは「error」を生成します。
$("#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);
}
});
のajaxSetup
ようにステータスコードを定義できます
$.ajaxSetup({
statusCode: {
404: function() {
alert("page not found");
//load the 404 page here
}
}
});