[英]jQuery Plugin with $.getJSON Returning undefined?
在jQuery插件內部,我有:
$.getJSON(base_url,{
agenda_id:defaults.id,
action:defaults.action+defaults.type,
output:defaults.output
},function(json){
return json;
});
並在一個單獨的JS文件中(是的,它在插件之后):
json = $('#agenda-live-preview').agenda({action:'get',type:'agenda',output:'json'});
alert(json[0].agenda_id);
如果我執行上述$ .getJSON並將警報放在$ .getJSON內,則它會工作並返回“ 3”,這是正確的。 如果我這樣做像json=$('#agenda-live-preview').agenda(...)...
它將返回未定義的內容。
我的JSON有效,並且json [0] .agenda_id也正確,我知道它在回調中,那么如何在函數返回的回調中獲取內容?
由於默認情況下AJAX請求是異步的,因此alert()
在接收到AJAX請求之前正在運行,因此未為json
變量分配值。
無論您想要什么功能(例如警報),都必須在AJAX請求的回調中,或者在回調中調用的函數中,或者可能使用.ajaxSuccess()
調用。
或者,您可以將函數作為參數傳遞給插件,然后讓$.getJSON()
回調對其進行調用。
編輯:
傳遞回調以成功執行$.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.