1

何をロードするかを決定するためにパラメータを取る小さな関数(以下)があります。404 に遭遇した場合、.load() の種類が「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」または「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);
  }
});
于 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 に答える