Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

html - How to Check if URL exists using javascript

I need to check if a URL exists and redirect a user if it's not, we support various browsers (IE, Chrome, Firefox etc...) so the solution needs to be able to support all of those.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the header of your page, place this javascript code:

        <script type="text/javascript">

        // Creates an object which can read files from the server
        var reader = new XMLHttpRequest();

        var checkFor = "fileToCheckFor.html";

        // Opens the file and specifies the method (get)
        // Asynchronous is true
        reader.open('get', checkFor, true);

        //check each time the ready state changes
        //to see if the object is ready
        reader.onreadystatechange = checkReadyState;

        function checkReadyState() {

            if (reader.readyState === 4) {

                //check to see whether request for the file failed or succeeded
                if ((reader.status == 200) || (reader.status == 0)) {

                //page exists -- redirect to the checked
                //checked for page
                document.location.href = checkFor;

                }
                else {

                //does nothing and quits the function
                //if the url does not exist
                return;

                }

            }//end of if (reader.readyState === 4)

        }// end of checkReadyState()

        // Sends the request for the file data to the server
        // Use null for "get" mode
        reader.send(null);

    </script>


This allows you to check whether or not a page exists on your server and redirect to it if it does. If the page does not exist, the javascript code does nothing and allows the current page to load.

Edit: Fixed bugs and rewrote some of the code for clarity, appearance, and practicality.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...