[英]jQuery Plugin with $.getJSON Returning undefined?
Inside of a jQuery plugin I made I have: 在jQuery插件内部,我有:
$.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): 并在一个单独的JS文件中(是的,它在插件之后):
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. 如果我执行上述$ .getJSON并将警报放在$ .getJSON内,则它会工作并返回“ 3”,这是正确的。 If I do it like the
json=$('#agenda-live-preview').agenda(...)...
it returns undefined. 如果我这样做像
json=$('#agenda-live-preview').agenda(...)...
它将返回未定义的内容。
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? 我的JSON有效,并且json [0] .agenda_id也正确,我知道它在回调中,那么如何在函数返回的回调中获取内容?
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. 由于默认情况下AJAX请求是异步的,因此
alert()
在接收到AJAX请求之前正在运行,因此未为json
变量分配值。
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()
. 无论您想要什么功能(例如警报),都必须在AJAX请求的回调中,或者在回调中调用的函数中,或者可能使用
.ajaxSuccess()
调用。
Or perhaps you could pass a function as a parameter to your plugin, and have the $.getJSON()
callback call it. 或者,您可以将函数作为参数传递给插件,然后让
$.getJSON()
回调对其进行调用。
EDIT: 编辑:
Example of passing in a callback to run upon successful $.getJSON()
request: 传递回调以成功执行
$.getJSON()
请求的$.getJSON()
:
$.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 );
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.