سؤال

I'm writing my first jQuery plugin and looking for some help making a JSONP request inside it.

Normally I setup my JSON data inside of a callback function like so

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

Then on a page I call .getJSON() like so:

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

And set up the callback function

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

And everything works fine. How would I get this to work inside my plugin? If I do it like it is below, I'm getting a "Uncaught ReferenceError: saveDataCommunityPartners is not defined" error.

(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));

I can either change the plugin, or how I set up the JSON file itself, whatever is recommended. Thanks!

هل كانت مفيدة؟

المحلول 2

Got it working using 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);
    }
});

Note that originally in the success function I tried to store the json in a variable called data like so: data = json;, but ran into problems as this does not ensure that the json will have returned by the time data could be accessed. See this question for more info on that end.

نصائح أخرى

The getJSON method has a callback feature that you can use.

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

saveDataCommunityPartners(data);

});

OR use the chained command

$.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);

})

You can also relocate the saveDataCommunityPartners function outside the JQuery container if the error still persists.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top