Checking a Url in Jquery/Javascript

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

    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.

提交回复
热议问题