使用.ajax()和JSONP的基本示例?

sim*_*mon 183 ajax json 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,
    });
});
Run Code Online (Sandbox Code Playgroud)

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

应该产生一个警报,据我可以从文档中解决:不是(但也没有产生任何错误).

谢谢.

Tha*_*Guy 384

JSONP实际上是克服XMLHttpRequest相同域策略的简单技巧.(如您所知,无法将AJAX(XMLHttpRequest)请求发送到其他域.)

所以 - 我们不得不使用XMLHttpRequest,而是使用脚本 HTMLl标签,这些标签通常用于加载JS文件,以便JS从另一个域获取数据.听起来怪怪的?

事情是 - 结果脚本标签可以像XMLHttpRequest类似的方式使用!看一下这个:

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

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

<script>
{['some string 1', 'some data', 'whatever data']}
</script>
Run Code Online (Sandbox Code Playgroud)

但是这有点不方便,因为我们必须从脚本标记中获取此数组.所以JSONP创建者决定这会更好(并且它是):

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

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

my_callback({['some string 1', 'some data', 'whatever data']});
Run Code Online (Sandbox Code Playgroud)

看看利润在哪里:现在我们得到自动回调(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>
Run Code Online (Sandbox Code Playgroud)


基本的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>
Run Code Online (Sandbox Code Playgroud)


JSONP代表带有填充的JSON.(技术名称很差,因为它与大多数人认为的"填充"无关.)

  • "成功:"对我不起作用,但是"完成" (7认同)
  • 如果您想让这些脚本生产就绪,您需要考虑什么? (4认同)
  • 这个答案现在已经过时了,因为浏览器现在支持`Access-Control-Allow-Origin`标题,允许对某些跨域域进行常规Ajax调用. (3认同)
  • 请记住,您不能使用 JSONP 执行表单 POST。更多信息:http://www.markhneedham.com/blog/2009/08/27/jquery-post-jsonp-and-cross-domain-requests/ (2认同)

Pet*_*ler 144

如何使用jQuery使用JSONP更简单

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

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

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

  • 最后一次编辑是什么,"请不要再使用jQuery!" 意思? (3认同)
  • 这是一个非常好的jQuery技巧,谢谢. (2认同)
  • @PetrPeller,看起来很棒,但我似乎没有用它制作产品.你能看到这个吗?[JSFiddle](http://jsfiddle.net/Az9SS/)它不会提醒任何数据.也许我错过了什么 (2认同)
  • @PetrPeller我对你的解决方案非常感兴趣。但是,这对我不起作用。我不想发布新问题,但这对我没有帮助。**服务器似乎不支持**是什么意思?我应该怎么办?您能给我一个适用于我的服务器的完整 URL 吗?我会很感激你的。_我需要任何服务器配置吗?_ (2认同)

Pap*_*eud 27

响应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);
};
Run Code Online (Sandbox Code Playgroud)

虽然alert()像这样的数组并不能很好地工作...... Firebug中的"Net"选项卡将正确显示JSON.另一个方便的技巧是做

alert(JSON.stringify(data));
Run Code Online (Sandbox Code Playgroud)

您还可以使用jQuery.getJSON方法.这是一个完整的html示例,它从github获取"gists"列表.这样它会为你创建一个随机命名的回调函数,这是最后的"回调=?" 在网址中.

<!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>
Run Code Online (Sandbox Code Playgroud)

  • 你是对的,它不再起作用了.Twitter改变了他们的API. (2认同)