将 .ajax() 与 JSONP 一起使用的基本示例? [英] Basic example of using .ajax() with JSONP?

查看:36
本文介绍了将 .ajax() 与 JSONP 一起使用的基本示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请有人帮我弄清楚如何开始使用 JSONP?

Please could someone help me work out how to get started with JSONP?

代码:

$('document').ready(function() {
    var pm_url = 'http://twitter.com/status';
    pm_url += '/user_timeline/stephenfry.json';
    pm_url += '?count=10&callback=photos';
    var photos = function (data) {
     alert(data);
    };
    $.ajax({
        url: pm_url,
        dataType: 'jsonp',
        jsonpCallback: 'photos',
        jsonp: false,
    });
});

小提琴:http://jsfiddle.net/R7EPt/6/

就我可以从文档中得出的结论而言,应该产生警报:不是(但也不会产生任何错误).

Should produce an alert, as far as I can work out from the documentation: isn't (but isn't producing any errors either).

谢谢.

推荐答案

JSONP 确实是克服 XMLHttpRequest 相同域策略的简单技巧.(如您所知,不能将 AJAX (XMLHttpRequest) 请求发送到不同的域.)

JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)

所以 - 我们必须使用 script HTMLl 标签而不是使用 XMLHttpRequest,这些标签通常用于加载 JS 文件,以便 JS 从另一个文件中获取数据领域.听起来很奇怪吗?

So - instead of using XMLHttpRequest we have to use script HTMLl tags, the ones you usually use to load JS files, in order for JS to get data from another domain. Sounds weird?

事情是 - 结果 script 标签可以以类似于 XMLHttpRequest 的方式使用!看看这个:

Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:

script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data";

加载数据后,您将得到一个脚本段,如下所示:

You will end up with a script segment that looks like this after it loads the data:

<script>
{['some string 1', 'some data', 'whatever data']}
</script>

但是这有点不方便,因为我们必须从 script 标签中获取这个数组.所以 JSONP 的创作者决定这会更好(而且确实如此):

However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better (and it is):

script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data?callback=my_callback";

注意那边的 my_callback 函数吗?所以 - 当 JSONP 服务器收到您的请求并找到回调参数时 - 它不会返回普通的 JS 数组,而是返回:

Notice my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain JS array it'll return this:

my_callback({['some string 1', 'some data', 'whatever data']});

看看利润在哪里:现在我们得到了自动回调(my_callback),一旦我们得到数据就会触发它.这就是关于 JSONP 的全部知识:它是一个回调和脚本标签.

See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data. That's all there is to know about JSONP: it's a callback and script tags.

注意:
这些是 JSONP 用法的简单示例,它们不是生产就绪的脚本.

RAW JavaScript 演示(使用 JSONP 的简单 Twitter 提要):

<html>
    <head>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
        <script>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            }
            document.getElementById('twitterFeed').innerHTML = text;
        }
        </script>
        <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
    </body>
</html>


基本 jQuery 示例(使用 JSONP 的简单 Twitter 提要):

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                        }
                        $('#twitterFeed').html(text);
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
    </body>
</html>


JSONP 代表 JSON with Padding.(非常糟糕的技术,因为它实际上与大多数人认为的填充"无关.)


JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as "padding".)

这篇关于将 .ajax() 与 JSONP 一起使用的基本示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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