Javascript 在页面加载时检测 404 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26630650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:08:51  来源:igfitidea点击:

detect 404 error on page load

javascripthttp-status-code-404

提问by MimiBambino

I am embedding a google map in my website and sometimes google responds with a 404 error. I know I should know this, but I can't remember and I cannot find it quickly. None of the other 404 iframe related questions on this site were ever answered.

我在我的网站中嵌入了 google 地图,有时 google 会以 404 错误响应。我知道我应该知道这一点,但我不记得了,也无法很快找到。本网站上其他与 404 iframe 相关的问题都没有得到回答。

How do I check if there is a 404 response in javascript? I plan to call location.reload() when the response is 404.

如何检查javascript中是否有404响应?我打算在响应为 404 时调用 location.reload()。

<iframe src="https://mapsengine.google.com/map/embed?mid=zGLD-nMIJQAg.k0gTyNlOPz_Q" width="640" height="480"></iframe>

The error code is:

错误代码是:

GET https://khms0.googleapis.com/kh?v=159&hl=en&x=784456&y=1636828&z=22&token=122715 404 (Not Found)

I tried this: It didn't help.

我试过这个:它没有帮助。

var url = 'https://mapsengine.google.com/map/embed?mid=zGLD-nMIJQAg.k0gTyNlOPz_Q';
if (url.statusCode === '404'){
    window.location.reload();
}

回答by Amit Guleria

var url = 'https://mapsengine.google.com/map/embed?mid=zGLD-nMIJQAg.k0gTyNlOPz_Q';
function UrlExists(url) {
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    if (http.status != 404)
        //  do something
    else
        window.location.reload();
}

Use this function and pass the URL as Parameter.if the status is not 404 then nothing will happen or you can do something else it will refresh the page as per your requirement.

使用此函数并将 URL 作为参数传递。如果状态不是 404,则不会发生任何事情,或者您可以执行其他操作,它将根据您的要求刷新页面。

回答by Adam Sparks

I know this is an old question, but here is an updated way of doing it with fetch (doesn't work on IE):

我知道这是一个老问题,但这里有一种使用 fetch 进行更新的方法(不适用于 IE):

function urlExists(url, callback) {
  fetch(url, { method: 'head' })
  .then(function(status) {
    callback(status.ok)
  });
}

let url = 'https://mapsengine.google.com/map/embed?mid=zGLD-nMIJQAg.k0gTyNlOPz_Q';

urlExists(url, function(exists) {
  if (exists) {
    // it exists, do something
  } else {
    // it doesn't exist, do something else
  }
});