Load special page if page doesn't exist (404)

2019-08-01 04:57发布

问题:

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();
}

Thanks in advance :)

回答1:

You can specify a function to be executed when the load completes.

Taken from the 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);
  }
});

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();
        };
    });
}

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 in the sample contains the error number 404 and the xhr.statusText is 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();
        };
    });
}

See DEMO



回答2:

.load() has responseText and textStatus parameters that tell you when it succeeds so you can use that to check if it fails. A successful response will generate "success" or "notmodified" while an error generates "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);
  }
});


回答3:

in the ajaxSetup you can define the status code like

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