开发者

Checking a Url in Jquery/Javascript

开发者 https://www.devze.com 2023-01-27 22:24 出处:网络
All I need is a method that returns true if the Url is responding. Unfortunately, I\'m new to jQuery and it\'s making my attempts at writing that method rather frustrating.

All I need is a method that returns true if the Url is responding. Unfortunately, I'm new to jQuery and it's making my attempts at writing that method rather frustrating.

I've seen several examples of jQuery using .ajax, but the code is consistently failing on me. What's wrong?

var urlExists = function(url){
    //When I call the function, code is still executing here.
    $.ajax({
        type: 'HEAD',
        url: url,
    开发者_如何学C    success: function() {
            return true;
        },
        error: function() {
            return false;
        }            
    });
    //But not here...
}


That isn't how AJAX works. AJAX is fundamentally asynchronous (that's actually what the first 'A' stands for), which means rather than you call a function and it returns a value, instead you call a function and pass in a callback, and that callback will be called with the value.

(See http://en.wikipedia.org/wiki/Continuation_passing_style.)

What do you want to do after you know whether the URL is responding or not? If you intended to use this method like this:

//do stuff
var exists = urlExists(url);
//do more stuff based on the boolean value of exists

Then what you instead have to do is:

//do stuff
urlExists(url, function(exists){
  //do more stuff based on the boolean value of exists
});

where urlExists() is:

function urlExists(url, callback){
  $.ajax({
    type: 'HEAD',
    url: url,
    success: function(){
      callback(true);
    },
    error: function() {
      callback(false);
    }
  });
}


urlExists() can not return because it needs wait for the request.

Either pass it a callback, or make it synchronous (not recommended, because it locks the browser).

var urlExists = function(url, callback) {

    if ( ! $.isFunction(callback)) {
       throw Error('Not a valid callback');
    }   

    $.ajax({
        type: 'HEAD',
        url: url,
        success: $.proxy(callback, this, true),
        error: $.proxy(callback, this, false)      
    });

};

Then you can do

urlExists('/something', function(success) {
    if (success) {
        alert('Yay!');
    } else {
        alert('Oh no!');
    }
});

It also worth mentioning the same origin policy.

Also, returning from an anonymous function's scope will not return in the parent function (like in your original example). It just returns that inner function. To return from an inner to a parent, set a flag and return it.


Basically, there is nothing wrong with your code. See it work here: http://jsfiddle.net/PK76X/

My guess is that you're using it to check the availability of content on a different domain, which fails because browsers don't allow cross domain ajax-requests.


If the url is from the same domain as your page you can do it. But if it is from a different domain, for example google.com, then it will fail due to cross domain security.


In general, you should probably run your script in Firefox using the firebug plugin. It will give you the details needed to solve the issue.

The ajax and post methods are asynchronous, so you should handle the result in a callback method.


AJAX is basically asynchronous, and that's why the behavior you are describing. I've used the following, which is free of cross origin, to get a simple true/false indication whether a URL is valid, in a synchronous manner:

function isValidURL(url) {
    var encodedURL = encodeURIComponent(url);
    var isValid = false;

    $.ajax({
      url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
      type: "get",
      async: false,
      dataType: "json",
      success: function(data) {
        isValid = data.query.results != null;
      },
      error: function(){
        isValid = false;
      }
    });

    return isValid;
}

The usage is then trivial:

var isValid = isValidURL("http://www.wix.com");
alert(isValid ? "Valid URL!!!" : "Damn...");

Hope this helps

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号