跨域jquery获取 [英] cross domain jquery get

查看:21
本文介绍了跨域jquery获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了一些使用 ajax 进行跨域的示例,但它不起作用.

I saw some examples of cross domain with ajax but it doesn't work.

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    </head>
    <body>
        <script type="text/javascript" >
            $(document).ready(function () {
                var url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=AssasNet&include_rts=1";

                $.get(url, function (data) {
                    console.log(data)
                    alert(data);
                });
            });
        </script>
    </body>
</html>

我在 chrome 上尝试并给出以下错误:

I try on chrome and the following error is given:

XMLHttpRequest cannot load http://api.twitter.com/1/statuses/user_timeline.json?screen_name=AssasNet&include_rts=1. Origin null is not allowed by Access-Control-Allow-Origin. 

推荐答案

你不能使用 $.get 因为它会执行一个 ajax 调用,这将是跨域的,因此被同源政策,并且您尝试访问的 Twitter API 不支持 跨源资源共享(如果有,则不允许 origin nullhttp://jsbin.com,这是我试过的).

You can't use $.get because that does an ajax call, which will be cross-origin and thus blocked by the Same Origin Policy, and the Twitter API you're trying to access doesn't support Cross-Origin Resource Sharing (or if it does, it doesn't allow either origin null or http://jsbin.com, which is the one I tried).

API 确实支持 JSONP(这不是真正的 ajax 调用),所以只需更改$.get$.ajax 指定 JSONP 作品:

The API does support JSONP (which is not a true ajax call), though, so just changing the $.get to an $.ajax specifying JSONP works:

$.ajax({
  url: url,
  dataType: "jsonp",
  success: function (data) {
    console.log(data)
    alert(data);
  }
});

现场示例 |来源

这篇关于跨域jquery获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆