检查 Javascript 中的 URL 是否损坏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3915634/
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-23 06:37:22  来源:igfitidea点击:

Checking if a URL is broken in Javascript

javascriptjqueryhttp

提问by Trip

This question has been posted on Stack before, but none so specific as to what I'm trying to understand.

这个问题之前已经在 Stack 上发布过,但没有像我想要理解的那样具体。

The simplest way to check if a URL is corrrect to send a http Head request. But how do you use that to specify the URL ?

检查 URL 是否正确发送 http Head 请求的最简单方法。但是你如何使用它来指定 URL 呢?

I found this in a previous post :

我在以前的帖子中找到了这个:

function UrlExists(url) {
  var http = new XMLHttpRequest();
  http.open('HEAD', url, false);
  http.send();
  return http.status!=404;
}

But it doesn't seem to run in firebug for a few reasons.

但由于一些原因,它似乎并没有在 firebug 中运行。

My apologies ahead of time for being daft.

我为自己的愚蠢提前道歉。

回答by jAndy

I'd recommend to use jQuery for correct cross-browser ajax requests:

我建议将 jQuery 用于正确的跨浏览器 ajax 请求:

function UrlExists(url, cb){
    jQuery.ajax({
        url:      url,
        dataType: 'text',
        type:     'GET',
        complete:  function(xhr){
            if(typeof cb === 'function')
               cb.apply(this, [xhr.status]);
        }
    });
}

Usage:

用法:

UrlExists('/path/script.pl', function(status){
    if(status === 200){
       // file was found
    }
    else if(status === 404){
       // 404 not found
    }
});