本文介绍了实施 Google URL Shorter API 的跨域问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 AJAX 调用在 jQuery 的帮助下实现 Google 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 url 参数以调用您的新代理脚本而不是 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.

这篇关于实施 Google URL Shorter API 的跨域问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 23:31