5

我正在尝试通过 AJAX 调用在 jQuery 的帮助下实现 Google URL Shorter 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 方法不允许”。我在这里做错了吗?

4

3 回答 3

17

在 Javascript 中,这里有两种实现 Google URL Shorter API 的方法:

方法 #1:使用 jsonlib,http://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("<BR>Short Url: "+s); });

方法#2:使用谷歌客户端库,https://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);
        }
    });
});
于 2011-12-30T16:59:22.873 回答
5

恐怕你确实是。由于浏览器的安全性,您不能进行跨域 ajax 调用。

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

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

于 2011-01-14T12:18:55.870 回答
0

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

但是,该方法在我的情况下效果很好。参考这里的一个很好的例子。方法有点棘手。

于 2011-01-14T12:41:41.243 回答