实施Google URL缩短程序API的跨域问题

我试图通过进行AJAX调用在jQuery的帮助下实现Google URL缩短器API。 我做过这样的事情:

$(function() { $('#btnshorten').click(function() { var longURL = $('#tboxLongURL').val(); $.ajax({ url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw', type: 'POST', contentType: 'application/json; charset=utf-8', data: '{ longUrl: "' + longURL +'"}', dataType: 'json', success: function(response) { var result = eval(response); // Evaluate the J-Son response object. } }); }); }); 

但它在IE中产生错误。 它显示“访问被拒绝”,在Firebug中显示“405方法不被允许”。 我在这里做错了吗?

你确实是,我很害怕。 由于浏览器安全性,您无法进行跨域ajax调用。

我知道Ext JS提供了一个可以完成工作的ScriptTagProxy对象,但是我不确定jQuery是否有类似的东西。

另一种方法是在您自己的主机上创建一种“代理”服务器端脚本,该脚本可以接受来自您的ajax调用的参数,创建HttpWebRequest或类似于googleapis.com并输出响应以便您再次获取ajax电话。 然后只需修改您的ajax url参数即可调用新的代理脚本而不是googleapis。 换句话说 – 让服务器端执行跨域请求。

在Javascript中,以下是实现Google URL缩短器API的两种方法:

方法#1:使用jsonlib, http://call.jsonlib.com/jsonlib.js ://call.jsonlib.com/jsonlib.js在这里试试: 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); });

方法#2:使用谷歌客户端库, https://apis.google.com/js/client.js : //apis.google.com/js/client.js ,在这里试试: 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); } }); }); 

您可以使用动态脚本标记来进行跨域ajax调用。 正如此处所指出的,这种方法存在一些问题:很难知道内容何时可用,没有标准方法,并且可以被视为“安全风险”。

然而,在我的情况下,该方法工作正常。 请参考这里的一个好例子。 这种方法有点棘手。