【问题标题】:JSONP Callback Function inside jQuery PluginjQuery插件内的JSONP回调函数
【发布时间】:2014-07-03 05:52:05
【问题描述】:

我正在编写我的第一个 jQuery 插件并寻求一些帮助,以便在其中发出 JSONP 请求。

通常我在这样的回调函数中设置我的 JSON 数据

saveDataCommunityPartners({
    "newsBlockItems": [
        {
            "title": "title title title",
            "img": "item-img.jpg"
        },
        {
            "title": "title title title",
            "img": "item-img.jpg"
        }
        ... and so on and so forth
    ]
})

然后在一个页面上我这样调用.getJSON()

$.getJSON("http://i.cdn.turner.com/nba/nba/.element/media/2.0/teamsites/warriors/json/json-redesign-communitypartners.js?callback=?");

并设置回调函数

function saveDataCommunityPartners(data) {
    alert("got data");
}

一切正常。我如何让它在我的插件中工作?如果我像下面那样做,我会收到“未捕获的 ReferenceError:未定义 saveDataCommunityPartners”错误。

(function($) {
    $.fn.createNewsBlock = function( options ) {
        // Establish defaults
        var settings = $.extend({
        thisData        : {},
        pageFilter      : "community"
    }, options);

    $.getJSON("http://i.cdn.turner.com/nba/nba/.element/media/2.0/teamsites/warriors/json/json-redesign-communitypartners.js?callback=?");

    function saveDataCommunityPartners(data) {
        alert("got data");
    }
}(jQuery));

我可以更改插件,或者我如何设置 JSON 文件本身,无论推荐什么。谢谢!

【问题讨论】:

    标签: jquery ajax jquery-plugins jsonp getjson


    【解决方案1】:

    使用this code from here

    $.ajax({
        type: 'GET',
        url: "http://i.cdn.turner.com/nba/nba/.element/media/2.0/teamsites/warriors/json/json-redesign-communitypartners.js?callback=?",
        async: false,
        jsonpCallback: 'saveDataCommunityPartners',
        contentType: "application/json",
        dataType: 'jsonp',
        success: function(json) {
            parseJSON(json); // pass to function to use for whatever
        },
        error: function(e) {
            console.log(e.message);
        }
    });
    

    请注意,最初在成功函数中,我尝试将 json 存储在一个名为 data 的变量中,如下所示:data = json;,但遇到了问题,因为这不能确保 json 在data 可以返回时被访问。有关这方面的更多信息,请参阅this question

    【讨论】:

      【解决方案2】:

      getJSON 方法有一个可以使用的回调功能。

      $.getJSON("http://i.cdn.turner.com/nba/nba/.element/media/2.0/teamsites/warriors/json/json-redesign-communitypartners.js?callback=?",function(data){
      
      saveDataCommunityPartners(data);
      
      });
      

      或者使用链式命令

      $.getJSON("http://i.cdn.turner.com/nba/nba/.element/media/2.0/teamsites/warriors/json/json-redesign-communitypartners.js?callback=?").done(function( data ) {
      
      saveDataCommunityPartners(data);
      
      })
      

      如果错误仍然存​​在,您还可以将 saveDataCommunityPartners 函数重新定位到 JQuery 容器之外。

      【讨论】:

      • hm 这些似乎都不起作用(得到相同的错误)。我基本上只需要将数据存储在一个变量中。我需要在 jQuery 容器中执行此操作,因为插件需要解析数据以找到一些东西
      猜你喜欢
      • 1970-01-01
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      • 2019-12-07
      • 1970-01-01
      相关资源
      最近更新 更多