Ajax Google URL Shortener
4 de abril de 2011
Although it is very simple, I haven’t found any example out there. This is a little JS class to call Google URL Shortener API from your widget.
It requires jQuery. Notice that it won’t work on your Web site, it is only for widgets.
/** * @author Julio Rabadán (@ somms.net) */ var UrlShortener = function (_ApiKey) { this._apiKey = _ApiKey; }; UrlShortener.prototype.getShortURL = function (_URL, _callback){ _URL = $.trim(_URL); if(_URL){ var api_url = "https://www.googleapis.com/urlshortener/v1/url"; var data_POST = '{ "longUrl" : "' + _URL + '", "key" : "' + this._apiKey + '"}'; $.ajax({ url : api_url, dataType : "json", data : data_POST, contentType : "application/json", processData : false, success : function(response){ _callback(response); }, cache : true, error : function(XMLHttpRequest, textStatus, errorThrown){ console.log(XMLHttpRequest, textStatus, errorThrown); _callback({"status": "network_error"}); }, type : "POST" }); }else{ return false; } }
febrero 15th, 2012 at 12:27 pm
usando jsonlib puedes usarlo en cualquier web
function googlurl(url, cb) {
jsonlib.fetch({
url: ‘https://www.googleapis.com/urlshortener/v1/url’,
header: ‘Content-Type: application/json’,
data: JSON.stringify({longUrl: url, key:’tu_key’})
}, function (m) {
var result = null;
try {
result = JSON.parse(m.content).id;
if (typeof result != ‘string’) result = null;
} catch (e) {
result = null;
}
cb(result);
});
}