简体   繁体   中英

jQuery and Google URL Shortener API

I'm trying to shorten a URL using the http://goo.gl API with the following jQuery function

$.ajax({
        url: 'https://www.googleapis.com/urlshortener/v1/url?key=MY_API_KEY',
        crossDomain: true,
        type: 'POST',
        contentType: 'application/json',
        data: '{longUrl:"'+encodeURI(url)+'"}',
        dataType: 'jsonp',
        success: function(e) {
            alert(JSON.stringify(e));
        }
     });

And I get the following Error in JSON:

{"error":{"errors":[{"domain":"global","reason":"required","message":"Required parameter: shortUrl","locationType":"parameter","location":"shortUrl"}],"code":400,"message":"Required parameter: shortUrl"}}

Why does it ask for a Short URL? What am I doing wrong?

You can't do a cross-domain POST in JavaScript. What jQuery actually does when you mention crossDomain to be true and the dataType to be jsonp is a jsonp request, which is just a hack to get data from another server using a tag. You get that error because it's as if you had just done a GET requets on the API page with no parameters. The other server needs to be aware of this and needs to support it.

The Goo.gl API page has no mention of jsonp at all which makes me believe it doesn't support it. Your best bet would be to write a proxy in PHP to do the requets for you and return the result, and then do an Ajax call on that PHP file.

Edit: If it's a Chrome extension, you can do a cross-domain Ajax call using a special Chrome method to get the URL to pass to the Ajax object. You also need to add the remote URL to your extension manifest file, as documented here.

Here's a working code.

$.ajax({
        url: 'https://www.googleapis.com/urlshortener/v1/url?key={API-KEY}',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: '{ longUrl: "' + longURL +'"}',
        success: function(response) {
            $('#inputBox').val(response.id);
        }
     });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM