如何使用javascript检查URL是否存在 [英] How to Check if URL exists using javascript

查看:127
本文介绍了如何使用javascript检查URL是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

在页面的标题中,放置以下javascript代码:

 < script type =text / javascript> 

//创建一个可以从服务器读取文件的对象
var reader = new XMLHttpRequest();

var checkFor =fileToCheckFor.html;

//打开文件并指定方法(get)
// Asynchronous is true
reader.open('get',checkFor,true);

//检查每次准备状态变化
//查看对象是否准备就绪
reader.onreadystatechange = checkReadyState;

函数checkReadyState(){

if(reader.readyState === 4){

//检查是否请求文件失败或成功
if((reader.status == 200)||(reader.status == 0)){

//页面存在 - 重定向到
//检查页面
document.location.href = checkFor;

}
else {

//不执行任何操作并退出函数
//如果url不存在
return;


$ b} // if(reader.readyState === 4)

} // end of checkReadyState()

//将文件数据的请求发送到服务器
//对于get模式使用null
reader.send(null);

< / script>



这可让您检查服务器上是否存在页面如果有的话,重定向到它。如果页面不存在,那么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.

解决方案

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.

这篇关于如何使用javascript检查URL是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆