如何使用Javascript检查页面是否存在 [英] How to check if page exists using Javascript

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

问题描述

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

当我点击链接时,应检查页面是否存在。如果它存在则进入该页面(www.example.com),但如果页面不存在,则重定向到另一个URL。

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.

推荐答案

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

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).

如果 在同一个域上,你可以像Buh Buh建议的那样使用jQuery。虽然我建议做一个HEAD请求而不是GET请求默认的 $ .ajax()方法 - $ .ajax( )方法将下载整个页面。执行HEAD请求将仅返回标题并指示页面是否存在(响应代码200-299)或不响应(响应代码400-499)。示例:

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

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

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

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