将.ajax()与JSONP结合使用的基本示例?

将.ajax()与JSONP结合使用的基本示例?,ajax,json,jsonp,Ajax,Json,Jsonp,请有人帮我弄清楚如何开始使用JSONP吗 代码: 小提琴: 据我从文档中了解,应该会生成一个警报:不是(但也不会产生任何错误) 谢谢 JSONP实际上是克服XMLHttpRequest相同域策略的简单技巧。(正如您所知,不能向其他域发送AJAX(XMLHttpRequest)请求。) 因此,我们必须使用scriptHTMLl标记,而不是使用XMLHttpRequest,这些标记通常用于加载JS文件,以便JS从另一个域获取数据。听起来怪怪的 事实是,script标记可以以类似于XMLHttpReq

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

代码:

小提琴:

据我从文档中了解,应该会生成一个警报:不是(但也不会产生任何错误)


谢谢

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

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

事实是,script标记可以以类似于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服务器收到您的请求并找到回调参数时-它将返回以下内容,而不是返回普通JS数组:

my_callback({['some string 1', 'some data', 'whatever data']});
看看利润在哪里:现在我们得到了自动回调(my_callback),一旦我们得到数据就会被触发。 这就是关于JSONP的所有知识:它是一个回调和脚本标记


注意:
这些是JSONP使用的简单示例,它们不是可用于生产的脚本。

原始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>
<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>

函数myCallback(dataWeGotViaJsonp){
var text='';
var len=dataWeGotViaJsonp.length;

对于(var i=0;i,为了响应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中的“Net”选项卡将正确地显示JSON

alert(JSON.stringify(data));
您还可以使用jQuery.getJSON方法。下面是一个完整的html示例,它从github获取一个“gist”列表。这样,它会为您创建一个随机命名的回调函数,即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>

JQuery(跨域)JSONP Twitter示例
$(文档).ready(函数(){
$.getJSON('https://api.github.com/gists?callback=?,函数(响应){
$。每个(响应、数据、功能(i、gist){
$(“#gists”).append(“
  • ”+gist.user.login+”()
  • ); }); }); });

      使用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自动注册并调用回调函数

      有关更多详细信息,请参阅。

      
      img{高度:100px;浮点:左;}
      JSONP示例
      $.getJSON(“http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
      {
      格式:“json”
      },
      //返回的响应数据被循环,并且只有图像被附加到图像DIV
      功能(数据){
      $.each(data.items,function(i,item){
      $("
      

      上面的代码有助于从Flicker API获取图像。这使用GET方法使用JSONP获取图像。可以在

      $.ajax({url:pm_url,dataType:'JSONP',jsonpCallback:photos,JSONP:false,})中找到详细信息;您已将照片作为字符串输入。没错,它不再工作。Twitter更改了它们的API。@PetrPeller,看起来不错,但我似乎没有用它制作产品。您能看到这个吗?它不会提醒任何数据。可能我错过了something@xDNP服务器必须支持JSONP响应。您的服务器似乎不支持它,因为我看不到此处添加的任何回调:。您也应该使用
      &callback=?
      ,因为它不是您案例中的第一个参数。@PetrPeller我对您的解决方案非常感兴趣。但是,这对我不起作用。我不想发布新问题,但它对我没有帮助。服务器似乎不支持什么意思?我应该怎么做?您能给我一些建议吗为我的服务器提供一个完整的URL?我将不胜感激。我需要任何服务器配置吗?最后编辑的是什么,“请不要再使用jQuery!”意思是?现在是2018年,我甚至不确定2017年应该使用什么!这个答案现在有些过时了,因为浏览器现在支持
      Access Control Allow Origin
      头,允许对一些跨源域进行常规Ajax调用。请记住,你不能用JSONP发布表单。这里的更多信息:你做了什么我想考虑一下,如果你想让这些脚本准备好吗?哇,这真的很有帮助!我终于知道JSONP到底是什么,它是如何工作的!
      <!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>
      
      $.getJSON("http://example.com/something.json?callback=?", function(result){
         //response data are now in the result variable
         alert(result);
      });
      
      <!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>