Checking a Url in Jquery/Javascript

前端 未结 6 2000
天涯浪人
天涯浪人 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:38

    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

提交回复
热议问题