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

ani*_*ish 22 javascript hyperlink

我有一个链接:<a href="http://www.example.com">Hello</a>.

当有人点击我想通过JavaScript检查的链接时,如果href-attribute指向的页面存在与否.如果页面存在,浏览器将重定向到该页面(在此示例中为"www.example.com"),但如果页面不存在,则浏览器应重定向到另一个URL.

fwi*_*tra 62

这取决于页面是否存在于同一域中.如果您正在尝试确定外部域上的页面是否存在,则它将无法工作 - 浏览器安全性会阻止跨域调用(同源策略).

如果在同一个域但是,您可以使用jQuery像寮步寮步建议.虽然我建议使用HEAD请求而不是默认$.ajax()方法的GET请求- 该$.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
}
});
Run Code Online (Sandbox Code Playgroud)

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


Par*_*ris 7

一个很好的解决方法是代理.如果您无权访问服务器端,则可以使用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
        });
Run Code Online (Sandbox Code Playgroud)

2017年8月2日更新

看起来雅虎不赞成"select*from html",尽管"select*from htmlstring"确实有效.


ste*_*tef 6

基于 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("/");
Run Code Online (Sandbox Code Playgroud)

然而,这仅适用于与当前 URL 相同域内的 URL。您希望能够 ping 通外部服务吗?如果是这样,您可以在服务器上创建一个简单的脚本来为您完成您的工作,并使用 javascript 来调用它。


epa*_*llo 2

如果是同一个域,可以用xmlhttprequest对象[ajax]发出head请求,并检查状态码。

如果它位于另一个域中,请向服务器发出 xmlhttprequest 并让它进行调用以查看它是否已启动。