Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

ajax - How to test a URL in jQuery

I have a URL which I want to open in a FancyBox (or any other overlay-type pop-up). I don't know in advance whether URL is good, so I want to test it. If invalid - I won't attach the fancyBox plugin to that particular URL, it will just be a regular link. How can I test a URL before attaching a plugin to it? Tried doing something like:

$("a.overlay").each(function() {
    var xhr = $.get(this.href, function(data, status) {
        // never executed in case of a failed request
    });
    if (xhr.status && xhr.status === 404)) {
        // not good, do nothing
    } else {
        // can attach plugin here
    }
});

The problem is, xhr will not always be defined because JS doesn't wait for the request to complete. Similarly, I cannot use the callback function, because it doesn't seem to be executing in case the request fails (I can see it in Firebug, but that's not very useful).

Thanks and have a good weekend everyone.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do it like this, although I would question how wise it is to make a request for each link....

$("a.overlay").each(function() {
    var $a = $(this);
    $.ajax({
        type: 'GET',
        url: this.href,
        success: function() {
            // attach plugin here
        },
        error: function() {
            // not good, log it
        }            
    });
});

If you're not going to do anything with the contents of the page, you could switch 'GET' with 'HEAD' to only get the headers of the page requested, which would be faster and let you know what you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...