简体   繁体   中英

Checking a Url in Jquery/Javascript

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,
        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, you call a function and pass in a callback, and that callback will be called with the value.

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

urlExists()<\/code> can not return because it needs wait for the request.

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

};

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

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM