如何检查页面是否存在使用Javascript

<a href="http://www.example.com">Hello</a> 

当我点击链接时,应该检查页面是否存在。 如果存在,则转到该页面(www.example.com),但如果该页面不存在,则redirect到另一个URL。

这取决于页面是否存在于同一个域中。 如果您尝试确定是否存在外部网页,则无法使用 – 浏览器安全性会阻止跨域呼叫(同源策略)。

如果它在同一个域上,你可以使用像Buh Buhbuild议的jQuery。 虽然我build议做一个HEAD请求,而不是GET请求,默认的$.ajax()方法会做 – $.ajax()方法将下载整个页面。 做一个HEAD请求将只返回标题,并指出页面是否存在(响应码200 – 299)或不响应(响应码400 – 499)。 例:

 $.ajax({ type: 'HEAD', url: 'http://yoursite.com/page.html', success: function() { // page exists }, error: function() { // page does not exist } }); 

另见: http : //api.jquery.com/jQuery.ajax/

一个相当不错的解决办法是代理。 如果您无法访问服务器端,则可以使用YQL。 访问: http : //developer.yahoo.com/yql/console/

从那里你可以做这样的事情: select * from htmlstring where url="http://google.com" 。 您可以使用他们在该页面上的“REST查询”作为您的代码的起点。

以下是一些代码,可以接受完整的URL并使用YQL来检测该页是否存在:

 function isURLReal(fullyQualifiedURL) { var URL = encodeURIComponent(fullyQualifiedURL), dfd = $.Deferred(), checkURLPromise = $.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlstring%20where%20url%3D%22' + URL + '%22&format=json'); checkURLPromise .done(function(response) { // results should be null if the page 404s or the domain doesn't work if (response.query.results) { dfd.resolve(true); } else { dfd.reject(false); } }) .fail(function() { dfd.reject('failed'); }); }); return dfd.promise(); } // usage isURLReal('http://google.com') .done(function(result) { // yes }) .fail(function(result) { // no, or request failed }); 

2017年8月2日更新

它看起来像雅虎弃用“select * from html”,虽然“select * from htmlstring”确实工作。

基于XMLHttpRequest的文档:

 function returnStatus(req, status) { //console.log(req); if(status == 200) { console.log("The url is available"); // send an event } else { console.log("The url returned status code " + status); // send a different event } } function fetchStatus(address) { var client = new XMLHttpRequest(); client.onreadystatechange = function() { // in case of network errors this might not give reliable results if(this.readyState == 4) returnStatus(this, this.status); } client.open("HEAD", address); client.send(); } fetchStatus("/"); 

但是,这只适用于与当前url位于同一网域的url。 你想能够ping外部服务吗? 如果是这样的话,你可以在服务器上创build一个简单的脚本,为你做好工作,并使用javascript来调用它。

如果它位于同一个域中,则可以使用xmlhttprequest对象[ajax]进行头部请求,并检查状态码。

如果它在另一个域中,则向服务器发出一个xmlhttprequest,并让它调用以查看它是否启动。

为什么不在Web服务器上创build一个自定义404处理程序? 这可能是更好的做法。

如果你很高兴使用jQuery,你可以做这样的事情。 当页面加载时,为每个链接做一个Ajax调用。 然后,只需replace失败的所有链接的href。

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <script type="text/javascript"> <!-- $.fn.checkPageExists = function(defaultUrl){ $.each(this, function(){ var $link = $(this); $.ajax({ url: $link.attr("href"), error: function(){ $link.attr("href", defaultUrl); } }); }); }; $(document).ready(function(){ $("a").checkPageExists("default.html"); }); //--> </script> 
 $.ajax({ url: "http://something/whatever.docx", method: "HEAD", statusCode: { 404: function () { alert('not found'); }, 200: function() { alert("foundfile exists"); } } }); 

另一种方法是使用PHP。

你可以添加

 <?php if (file_exists('/index.php')) { $url = '/index.php'; } else { $url = '/notindex.php'; } ?> 

接着

 <a href="<?php echo $url; ?>Link</a>