开发者

Why can't I call bit.ly API from JavaScript using jQuery's $.get function?

开发者 https://www.devze.com 2022-12-15 02:31 出处:网络
I tried to call bit.ly API using this jQuery script: $.get(\'http://api.bit.ly/shorten?login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&version=2.0.1&longUrl=www.wordpress.com

I tried to call bit.ly API using this jQuery script:

$.get('http://api.bit.ly/shorten?login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&version=2.0.1&longUrl=www.wordpress.com', function(data) {
    alert(data);
});

but firebug said "405 Method Not Allowed". What's wrong? Thanks a开发者_如何学运维 lot.


As mentioned already, standard AJAX call do not work cross domain. Just use JSONP with $.getJSON() instead.

Here is an example how to get a shortened URL with Bitly API and jQuery:

function get_short_url(long_url, login, api_key, func)
{
    $.getJSON(
        "http://api.bitly.com/v3/shorten?callback=?", 
        { 
            "format": "json",
            "apiKey": api_key,
            "login": login,
            "longUrl": long_url
        },
        function(response)
        {
            func(response.data.url);
        }
    );
}

The following code could be used to get a short URL:

/*
Sign up for Bitly account at
 https://bitly.com/a/sign_up

and upon completion visit
https://bitly.com/a/your_api_key/ 
to get "login" and "api_key" values
*/
var login = "LOGIN_HERE";
var api_key = "API_KEY_HERE";
var long_url = "http://www.kozlenko.info";

get_short_url(long_url, login, api_key, function(short_url) {
    console.log(short_url);
});


$.get do not support cross-domain GET.

You can use JSONP technique, and $.getJSON.

BTW, http:// should in the longUrl parameter of bit.ly API call. But it's not the main problem.


The reason you're seeing the 405 error is because you're violating the Same Origin Policy, which prevents retrieving data from a different domain, subdomain, or protocol.


The URL is not valid.

You have to put the http:// in front of the longUrl argument.

Edit

Some clarifications:

This url http://api.bit.ly/shorten?login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&version=2.0.1&longUrl=http://www.wordpress.com returns

{ "errorCode": 0, "errorMessage": "", "results": { "www.wordpress.com": { "errorCode": 1206, "errorMessage": "URL you tried to shorten was invalid.", "statusCode": "ERROR" } }, "statusCode": "OK" }

this one: http://api.bit.ly/shorten?login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&version=2.0.1&longUrl=http://www.wordpress.com returns

{ "errorCode": 0, "errorMessage": "", "results": { "http://www.wordpress.com": { "hash": "j1IP3", "shortKeywordUrl": "", "shortUrl": "http://bit.ly/6i1NkN", "userHash": "6i1NkN" } }, "statusCode": "OK" }


They probably expect a POST request rather than a GET.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号