How to check if page exists using Javascript

2019-01-02 15:57发布

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

when I click the link it should check whether the page exists or not. If it exists it goes to that page (www.example.com) but if the page doesn't exist it redirects to another URL.

8条回答
冷夜・残月
2楼-- · 2019-01-02 16:06

It depends on whether the page exists on the same domain or not. If you're trying to determine if a page on an external domain exists, it won't work – browser security prevents cross-domain calls (the same-origin policy).

If it is on the same domain however, you can use jQuery like Buh Buh suggested. Although I'd recommend doing a HEAD-request instead of the GET-request the default $.ajax() method does – the $.ajax() method will download the entire page. Doing a HEAD request will only return the headers and indicate whether the page exists (response codes 200 - 299) or not (response codes 400 - 499). Example:

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

See also: http://api.jquery.com/jQuery.ajax/

查看更多
步步皆殇っ
3楼-- · 2019-01-02 16:11

If you are happy to use jQuery you could do something like this. When the page loads make an ajax call for each link. Then just replace the href of all the links which fail.

<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> 
查看更多
千与千寻千般痛.
4楼-- · 2019-01-02 16:14

A pretty good work around is to proxy. If you don't have access to a server side you can use YQL. Visit: http://developer.yahoo.com/yql/console/

From there you can do something like: select * from htmlstring where url="http://google.com". You can use the "REST query" they have on that page as a starting point for your code.

Here's some code that would accept a full URL and use YQL to detect if that page exists:

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
        });

Update August 2nd, 2017

It looks like Yahoo deprecated "select * from html", although "select * from htmlstring" does work.

查看更多
不流泪的眼
5楼-- · 2019-01-02 16:14

If it is in the same domain, you can make a head request with the xmlhttprequest object [ajax] and check the status code.

If it is in another domain, make an xmlhttprequest to the server and have it make the call to see if it is up.

查看更多
不再属于我。
6楼-- · 2019-01-02 16:18

Based on the documentation for 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("/");

This will however only work for URLs within the same domain as the current URL. Do you want to be able to ping external services? If so, you could create a simple script on the server which does your job for you, and use javascript to call it.

查看更多
泛滥B
7楼-- · 2019-01-02 16:19

Another way to do this is is with PHP.

You could add

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

And then

<a href="<?php echo $url; ?>Link</a>
查看更多
登录 后发表回答