最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Disable HTML link if the URL's link returns an error - Stack Overflow

programmeradmin0浏览0评论

I have a button which links to another page. Before I click that link, I want to check if that page currently returns an error or if it is not existing. How can I code this? Is this possible? I want to disable the link if it is not existing or if it returns an error.

I have a button which links to another page. Before I click that link, I want to check if that page currently returns an error or if it is not existing. How can I code this? Is this possible? I want to disable the link if it is not existing or if it returns an error.

Share edited Aug 20, 2012 at 15:44 skynet 9,9085 gold badges45 silver badges52 bronze badges asked Aug 17, 2012 at 21:24 newbienewbie 15k33 gold badges108 silver badges149 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 3

You could use ajax to load the page and then parse it to see if there's an error before you then redirect the user. I would also include some kind of note to the user as to why the link isn't working.

Note that I'd do this on server side. However as your tags are related to jquery, I post a solution you may try with jquery.

using jquery you can:

var link = $('#id_of_your_a_element');
$.ajax(
    url: link.attr('href'),
    error: function() { 
        link.hide();
    }
);

EDIT

As ribot noted, this example does only hide the link. If you want to disable it you can prevent the default behavior when user clicks the link:

link.click(function(e) {
    e.preventDefault();
});

or alternatively just remove the href attribute:

link.removeAttr('href');

As someone had asked, what is the server side programming language you're using, if any?

Check out the answers here: How to get status code of remote url using Javascript/Ajax but NOT using jQuery?. Same question as this, and the answers cover all the bases.

Ajax on clicking every request, even if it's as HEAD request (which is what you generally SHOULD use to test for a url's existence as that's why that HTTP verb exists in the first place), just strikes me as an incredibly bad idea, even if you could get over the likely insurmountable cross domain issues (unless you involve some sort of server-side check invoked by ajax). Now, I suppose you might be able to save responses at some place so that links aren't rechecked (on both client or server side), but this strikes me still as an incredibly over-plicated solution to a problem that generally doesn't need solving.

发布评论

评论列表(0)

  1. 暂无评论