How to make a URL Shortener with the Bitly API wit

2019-03-05 05:29发布

I'm trying to make a URL Shortener tool for my web application using the Bitly API.

I found an SO thread here and saw what seemed to be simple enough jQuery solution.

getShortUrl: function(url, callback){
   var accessToken = //My access token, I've signed up at the site
   var url = 'https://api-ssl.bitly.com/v3/shorten?access_token=' + accessToken + '&longUrl=' + encodeURIComponent(url);

$.getJSON(
    url,
    {},
    function(response)
    {
        if(callback)
            callback(response.data.url);
    }
);
},

alert(getShortUrl("https://stackoverflow.com/search?q=URL+Shortener+JavaScript"))

I'm testing this out in chromium dev tools. The code doesn't error but the alert always comes out as undefined.

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-05 05:58

You aren't passing a callback and you get undefined because getShortUrl doesn't return anything.

Try this:

getShortUrl("http://stackoverflow.com/search?q=URL+Shortener+JavaScript",
    function (url) {
        alert(url);
    }
);
查看更多
登录 后发表回答