2011-05-09 16 views
169

请有人帮我解决一下如何开始使用JSONP?使用带有JSONP的.ajax()的基本示例?

代码:

$('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/

应该产生警报,据我可以从文档工作了:不是(但不产生任何错误,要么)。

谢谢。

+0

$阿贾克斯({ 网址:pm_url, 数据类型: 'JSONP', jsonpCallback:照片, JSONP:假的, });您以字符串形式输入了照片。 – wOlVeRiNe 2014-02-17 10:22:16

回答

361

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"; 

你会最终有一个脚本段,看起来像这样在加载数据后:

<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的示范(简单的Twitter饲料使用JSONP):

<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和Padding。 (名字很差,因为它实际上与大多数人认为的“填充”无关)。

+3

现在这个答案已经过时了,因为浏览器现在支持'Access-Control-Allow-Origin'头文件,它允许对一些跨域的域进行常规的Ajax调用。 – jfriend00 2015-03-13 02:41:32

+0

请记住,您无法使用JSONP执行表单POST。更多信息请看:http://www.markhneedham.com/blog/2009/08/27/jquery-post-jsonp-and-cross-domain-requests/ – 10basetom 2015-04-20 03:40:12

+6

'成功:'对我来说不起作用,但' complete' did – michalzuber 2015-05-12 11:17:26

24

响应OP,您的代码有两个问题:您需要设置jsonp ='回调“,并在像你这样的变量中添加回调函数似乎并不奏效。

更新:当我写这个时,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); 
}; 

虽然警报()荷兰国际集团的数组一样,并没有真正很好地工作... Firebug中的“Net”标签会正确显示JSON。另一个方便的技巧是做

alert(JSON.stringify(data)); 

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

<!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> 
+0

不,它不工作 – 2014-03-10 02:17:52

+2

你是对的,它不工作了。 Twitter更改了他们的API。 – PapaFreud 2014-03-13 17:04:28

135

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

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

?对URL的一端与JSONP工作告诉jQuery的,这是一个JSONP请求而不是JSON。 jQuery自动注册并调用回调函数。

欲了解更多详情请参考jQuery.getJSON documentation

编辑2017:请不要再使用jQuery!

+2

这是一个非常好的jQuery技巧要知道,谢谢。 – peabody 2014-01-17 08:12:23

+0

大伙伴!为什么这些ans没有被标记为有用的? – AK47 2014-05-22 11:23:07

+1

@PetrPeller,看起来不错,但我似乎没有制作出一款产品。你能看到这个吗? [JSFiddle](http://jsfiddle.net/Az9SS/)它没有提示数据。也许我错过了一些东西 – tika 2014-07-18 17:32:47

2
<!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> 

上述代码有助于从Flicker API获取图像。这使用GET方法来获取使用JSONP的图像。它可以详细here找到