【发布时间】:2012-11-28 04:41:05
【问题描述】:
我尝试填充全局变量 selectedDates 认为是第一个函数,但是当 我尝试获取一些值时它失败了,例如 selectedDates['1/23/2013']
尝试使用 $.ajax 而不是 $.get 后,我可以获得像 selectedDates['1/23/2013'] 这样的值。
如果它们都填充一个外部 var the_selected_dates 并返回到 set selectedDates,那么区别在哪里?
var selectedDates = {};
使用$.get 的函数失败:
function getSelectedDates_fails(lead_id, month) {
var the_selected_dates = {};
$.get(
window.location.href,
{
gf_lm_ajax : 1,
get : 'lead_reminder_get_dates',
lead_id : lead_id,
month : month,
nonce_gf_lm_ajax : gf_lmJsVars.nonce_gf_lm_ajax
},
function(output) {
$.each(output.reminders, function(n, val) {
the_selected_dates[val.date] = val.date;
});
}, 'json');
return the_selected_dates;
}
selectedDates = getSelectedDates_fails(35, 12); console.debug(selectedDates);
调试数据
使用$.ajax 的函数有效:
function getSelectedDates_works(lead_id, month) {
var the_selected_dates = {};
$.ajax(
{
url : window.location.href,
dataType : 'json',
data : {
gf_lm_ajax : 1,
get : 'lead_reminder_get_dates',
lead_id : lead_id,
month : month,
nonce_gf_lm_ajax : gf_lmJsVars.nonce_gf_lm_ajax
},
async : false,
success : function(output)
{
$.each(output.reminders, function(n, val) {
the_selected_dates[val.date] = val.date;
});
}
});
return the_selected_dates;
}
selectedDates = getSelectedDates_works(35, 12); console.debug(selectedDates);
调试数据
【问题讨论】:
-
是的,我正在使用一个对象
{}来模拟它。 -
Ajax 默认是异步的,你的 $.get 在函数返回空的
the_selected_dates对象之前不会完成。
标签: javascript jquery associative-array