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

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

问题描述

我有一个链接:<a href="http://www.example.com">你好</a>.

当有人点击链接时,我想通过 JavaScript 检查 href 属性指向的页面是否存在.如果该页面存在,浏览器将重定向到该页面(在本例中为www.example.com"),但如果该页面不存在,则浏览器应重定向到另一个 URL.

When someone clicks the link I'd like to check via JavaScript if the page the href-attribute points to exists or not. If the page exists the browser redirects to that page ("www.example.com" in this example) but if the page doesn't exist the browser should redirect 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天全站免登陆