将 .ajax() 与 JSONP 一起使用的基本示例



请有人帮我弄清楚如何开始使用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/

据我从文档中得出的,应该产生警报:不是(但也不会产生任何错误)。

谢谢。

JSONP实际上是克服XMLHttpRequest same域策略的简单技巧。(如您所知,不能将AJAX(XMLHttpRequest)请求发送到其他域。

因此,我们必须使用脚本HTMLl标签,而不是使用XMLHttpRequest,这些标签通常用于加载JS文件,以便JS从另一个域获取数据。听起来很奇怪?

事情是 - 事实证明脚本标签可以以类似于XMLHttpRequest的方式使用!看看这个:

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

加载数据后,您最终会得到如下所示的脚本段:

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

但是这有点不方便,因为我们必须从脚本标签中获取此数组。因此,JSONP创建者决定这将更好地工作(确实如此):

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

注意到那边my_callback功能了吗?所以 - 当 JSONP 服务器收到您的请求并找到回调参数时 - 而不是返回纯 JS 数组,它将返回以下内容:

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

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


注意:
这些是 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。(非常糟糕的命名技术,因为它实际上与大多数人认为的"填充"无关。

还有更简单的方法如何使用jQuery使用JSONP

$.getJSON("http://example.com/something.json?callback=?", function(result){
   //response data are now in the result variable
   alert(result);
});

URL末尾的?告诉jQuery这是一个JSONP请求而不是JSON。 jQuery自动注册并调用回调函数。

有关更多详细信息,请参阅 jQuery.getJSON 文档。

作为对 OP 的响应,您的代码存在两个问题:您需要设置 jsonp='callback',并且像您那样在变量中添加回调函数似乎不起作用。

更新:当我写这篇文章时,Twitter API 刚刚打开,但他们改变了它,现在需要身份验证。我将第二个示例更改为工作(2014Q1)示例,但现在使用github。

这不再有效 - 作为一个练习,看看你是否可以用 Github API 替换它:

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

尽管像这样的 alert()处理数组并不能很好地工作......Firebug 中的"网络"选项卡将正确显示 JSON。另一个方便的技巧是做

alert(JSON.stringify(data));

您也可以使用 jQuery.getJSON 方法。这是一个完整的 html 示例,它从 github 获取"gists"列表。通过这种方式,它会为您创建一个随机命名的回调函数,即 url 中的最后一个"callback=?"。

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>JQuery (cross-domain) JSONP Twitter example</title>
        <script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.getJSON('https://api.github.com/gists?callback=?', function(response){
                    $.each(response.data, function(i, gist){
                        $('#gists').append('<li>' + gist.user.login + " (<a href='" + gist.html_url + "'>" + 
                            (gist.description == "" ? "undescribed" : gist.description) + '</a>)</li>');
                    });
                });
            });
        </script>
    </head>
    <body>
        <ul id="gists"></ul>
    </body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
  format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
  $.each(data.items, function(i,item){
  $("<img/>").attr("src", item.media.m).appendTo("#images");
 });
});</script>
</body>
</html> 

上面的代码有助于从闪烁 API 获取图像。这使用 GET 方法使用 JSONP 获取图像。可以在这里找到详细的内容

最新更新