与谷歌实现URL缩短API跨域问题

问题描述:

我想实现与jQuery的帮助下通过一个AJAX调用谷歌URL缩短API。我做了这样的事情:

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() {
    $('#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方法。难道我做错了吗?

But it is generating an error in IE. It is showing "Access is denied" and in Firebug it is showing "405 method not allowed." Am I doing something wrong here?

事实上你,我害怕。你不能让,因为浏览器安全的跨域Ajax调用。

Indeed you are, I'm afraid. You can't make cross-domain ajax calls because of browser security.

我知道的Ext JS提供ScriptTagProxy对象,它可以做的工作,但我不知道是否jQuery有类似的事情。

I know that Ext JS offer a ScriptTagProxy object which can do the work, but I'm not sure if jQuery has anything similar.

另一种方法是你自己的主机上创建一种代理服务器端脚本,它可以接受从Ajax调用的参数,使一个HttpWebRequest的或相似的googleapis.com和输出的响应被拾起再由你的Ajax调用。然后,只需修改一个AJAX网址参数来调用你的新的代理脚本,而不是googleapis的。换句话说 - 让服务器端做跨域请求

An alternative would be to create a kind of "proxy" server-side script on your own host, which could accept parameters from your ajax call, make an HttpWebRequest or similar to googleapis.com and output the response to be picked up again by your ajax call. Then just modify your ajax url parameter to call your new proxy script instead of googleapis. In other words - let the server-side do the cross domain request.