JavaScript / jQuery检查断开的链接 [英] JavaScript/jQuery check broken links

查看:141
本文介绍了JavaScript / jQuery检查断开的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个小的Javascript / jQuery程序来访问内部使用的pdf文件集合。如果文件确实存在,我希望突出显示pdf文件的信息div。

I developed a small Javascript/jQuery program to access a collection of pdf files for internal use. And I wanted to have the information div of a pdf file highlighted if the file actually exist.

有没有办法以编程方式确定文件的链接是否被破坏?如果是这样,如何?

Is there a way to programmatically determine if a link to a file is broken? If so, How?

任何指南或建议都是适当的。

Any guide or suggestion is appropriated.

推荐答案

如果文件位于同一个域中,那么您可以使用AJAX测试它们的存在 Alex Sexton 说; 但是,您不应该使用 GET 方法,只需 HEAD ,然后检查HTTP期望值的状态(200,或者只是不到400)。

If the files are on the same domain, then you can use AJAX to test for their existence as Alex Sexton said; however, you should not use the GET method, just HEAD and then check the HTTP status for the expect value (200, or just less than 400).

这是一个从相关问题

function urlExists(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      callback(xhr.status < 400);
    }
  };
  xhr.open('HEAD', url);
  xhr.send();
}

urlExists(someUrl, function(exists) {
    console.log('"%s" exists?', someUrl, exists);
});

这篇关于JavaScript / jQuery检查断开的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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