简体   繁体   中英

How to Check if URL exists using javascript

我需要检查URL是否存在,如果不存在,请重定向用户,我们支持各种浏览器(IE,Chrome,Firefox等),因此该解决方案需要能够支持所有这些浏览器。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM