检查Javascript中的URL是否已损坏 [英] Checking if a URL is broken in Javascript

查看:109
本文介绍了检查Javascript中的URL是否已损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题之前已经发布在Stack上,但没有具体说明我想要理解的内容。

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

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

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 ?

我在上一篇文章中发现了这一点:

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

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

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

我很抱歉道歉。

推荐答案

我' d建议使用jQuery进行正确的跨浏览器ajax请求:

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

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

用法:

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

这篇关于检查Javascript中的URL是否已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆