简体   繁体   中英

jQuery Plugin with $.getJSON Returning undefined?

Inside of a jQuery plugin I made I have:

$.getJSON(base_url,{
    agenda_id:defaults.id,
    action:defaults.action+defaults.type,
    output:defaults.output
},function(json){
    return json;
});

And in a separate JS file (yes, it comes after the plugin):

json = $('#agenda-live-preview').agenda({action:'get',type:'agenda',output:'json'});
alert(json[0].agenda_id);

If i do the above $.getJSON and put an alert inside of the $.getJSON it works and returns "3", which is correct. If I do it like the json=$('#agenda-live-preview').agenda(...)... it returns undefined.

My JSON is valid, and the json[0].agenda_id is correct also, I know it's in a callback, so how do I get the stuff inside of a callback in a function return?

Because an AJAX request is asynchronous by default, the alert() is running before the AJAX request is received, and the json variable has therefore not been assigned a value.

Whatever functionality you want (the alert, for example) will need to be in the callback to the AJAX request, or will need to be in a function called from within the callback, or perhaps called using .ajaxSuccess() .

Or perhaps you could pass a function as a parameter to your plugin, and have the $.getJSON() callback call it.


EDIT:

Example of passing in a callback to run upon successful $.getJSON() request:

$.fn.agenda = function(opts) {

    var defaults = {...} // your defaults

    $.extend(defaults, opts); // Extend your defaults with the opts received

    $.getJSON(base_url,{
        agenda_id:defaults.id,
        action:defaults.action+defaults.type,
        output:defaults.output
    },function(json){
        defaults.success.call(this,json);  // Call the 'success' method passing in the json received
    });
};

$('#agenda-live-preview').agenda({
    action:'get',
    type:'agenda',
    output:'json',
    success:function(data) {  // Pass a function to the plugin's 'success' property
        alert(data[0].agenda_id);
        alert( $(this).selector );
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM