Cross Domain Issue with implementing Google URL shortener API

后端 未结 3 768
我在风中等你
我在风中等你 2021-01-03 02:23

I am trying to implement the Google URL shortener API with the help of jQuery by making an AJAX call. I have done something like this:

$(function() {
    $(         


        
3条回答
  •  清歌不尽
    2021-01-03 02:45

    In Javascript, here are 2 ways to to implement the Google URL shortener API:

    METHOD #1: Using jsonlib, http://call.jsonlib.com/jsonlib.js Try it out here: http://jsfiddle.net/Qh4eR/

    var longUrl = "http://google.com";
    document.write("Long Url: "+longUrl);
    
    function googlurl(url, cb) {
      jsonlib.fetch({
        url: 'https://www.googleapis.com/urlshortener/v1/url',
        header: 'Content-Type: application/json',
        data: JSON.stringify({longUrl: url})
      }, function (m) {
        var result = null;
        try {
          result = JSON.parse(m.content).id;
          if (typeof result != 'string') result = null;
        } catch (e) {
          result = null;
        }
        cb(result);
      });
    }
    googlurl(longUrl , function(s) { document.write("
    Short Url: "+s); });

    METHOD #2: Using the google client library, https://apis.google.com/js/client.js, Try it out here: http://jsfiddle.net/pPHKe/2/

    //var apiKey = 'YOUR_API_KEY';
    //gapi.client.setApiKey(apiKey);
    var longurl = 'http://www.google.com/';
    
    gapi.client.load('urlshortener', 'v1', function() {
        var request = gapi.client.urlshortener.url.insert({
            'resource': {
                'longUrl': longurl
            }
        });
        var resp = request.execute(function(resp) {
            if (resp.error) {
                $("#show").html('Error. ' + resp.error.message);
            } else {
                $("#show").html("Short URL for "+longurl+" is: " + resp.id);
            }
        });
    });
    

提交回复
热议问题