最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript redirect on 404 error - Stack Overflow

programmeradmin2浏览0评论

There is an external website which contains an html document for each day of the year, and I am trying to automatically load the document for the current date. However, the urls are not consistent across every document. Some of them end with .html while others end with .htm, and some of them might have a letter appended to the filename.

What I want to do is attempt to load a url, and if it results in a 404 error, try loading a different url.

For example, I might do window.location.replace(baseurl+'.htm'); and if that results in a 404 error, attempt window.location.replace(baseurl+'.html'); and if that results in a 404, try something else.

How can I determine when the server sends a 404 error and attempt to load a new url?

There is an external website which contains an html document for each day of the year, and I am trying to automatically load the document for the current date. However, the urls are not consistent across every document. Some of them end with .html while others end with .htm, and some of them might have a letter appended to the filename.

What I want to do is attempt to load a url, and if it results in a 404 error, try loading a different url.

For example, I might do window.location.replace(baseurl+'.htm'); and if that results in a 404 error, attempt window.location.replace(baseurl+'.html'); and if that results in a 404, try something else.

How can I determine when the server sends a 404 error and attempt to load a new url?

Share Improve this question edited Sep 16, 2016 at 15:30 krampstudio 3,6312 gold badges44 silver badges65 bronze badges asked Sep 16, 2016 at 14:22 ZarxraxZarxrax 951 silver badge5 bronze badges 1
  • 1 You can try with XHR before actually redirecting. Once you've redirected, your code will stop running and you're powerless to do anything about it. – Siguza Commented Sep 16, 2016 at 14:26
Add a ment  | 

2 Answers 2

Reset to default 2

Here's a function where you can pass in extensions to try, and it returns the first valid URL to a callback:

var request = new XMLHttpRequest();
var extensions = ['.html', '.htm'];
var count = 0;
var baseurl = 'http://blah./file';

function validUrl(baseurl, cb) {
  request.open('GET', baseurl + extensions[count], true);

  request.onreadystatechange = function() {
    if (request.readyState === 4) {
      if (request.status === 200) {
        cb(baseurl + extensions[count]);
      } else {
        count++;
        if (count === extensions.length) {
          cb(false);
        } else {
          validUrl(baseurl, cb);
        }
      }
    }
  };

  request.send();
}

// usage:

validUrl(baseurl, function(url) {
  if (url) {
    // use the valid url
  } else {
    console.log('no valid urls');
  }
});

As @Siguza said you can persist as an asynchronous request and validate it's status.

I suggest you to create a function which calls an AJAX and handle it's status returning to you if it's OK or not as a boolean. Something like:

// I'm  building an function to validate the URL
function checkValidURL(url) {
  var xmlhttp;
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
  } else {
    // code for older browsers
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }

  // Callback
  xmlhttp.onreadystatechange = function() {
    if (this.status == 200) {
      return true; // OK
    } else { // or -> } else if (this.status == 404) {
      return false; // Ops, something happen..
    }
  };
  // AJAX configuration
  xmlhttp.open("GET", url, false); // <- "false" for a synchronous request
  xmlhttp.send();
}

Simple example of use:

if (!checkValidURL("http://www.my_url")) {
    console.log("invalid URL"); 

    // Call or check other URL
} else {
    // It's OK, proceed with the business rules
}

Functions can wait AJAX requests by setting asynchronous "false", like: Is there any way to wait for AJAX response and halt execution?

发布评论

评论列表(0)

  1. 暂无评论