Checking a Url in Jquery/Javascript

前端 未结 6 2011
天涯浪人
天涯浪人 2020-12-03 01:58

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.<

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 02:50

    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.

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

提交回复
热议问题