javascript - 通过 $.ajax 和 $.get/$.post 填充关联数组的差异

标签 javascript jquery associative-array

我试图填充全局变量 selectedDates 认为是第一个函数,但是当我尝试获取一些值时它失败了,例如 selectedDates['1/23/2013']

尝试使用 $.ajax 而不是 $.get 后,我​​可以获得像 selectedDates['1/23/2013'] 这样的值。

如果它们都填充一个返回设置 selectedDates 的外部变量 the_selected_dates,区别在哪里?

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

调试数据

enter image description here

enter image description here

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

调试数据

enter image description here enter image description here

最佳答案

当您正在运行 $.ajax 同步 时,$.get 不是。

这就是为什么 getSelectedDates_fails() 返回的速度比您从服务器获得响应的速度快,因此返回一个空对象,{}

您在 selectedDates 中看到的是对象在异步完成请求之前的状态。


您可以使用 $.ajaxSetup()全局更改所有 $.ajax 调用的行为。但是,我不建议将 async 设置为 false

关于javascript - 通过 $.ajax 和 $.get/$.post 填充关联数组的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13806521/

相关文章:

javascript - jQuery UI - 拖放排序和恢复

awk - 在 awk 中预填充关联数组键?

php - 关联数组的 array_slice

javascript - JavaScript 中的 SecureRandom?

javascript - 有没有办法防止 neDB 集合数组中的条目重复?

jquery - 文本匹配不适用于阿拉伯语问题可能是由于阿拉伯语的正则表达式

javascript - Bootstrap 3 切换菜单

jquery - 如何从 jQuery.load() 响应中获取 body 元素?

php - 数组从旧PHP 4转换为5.6

javascript - 如何在Sequelize中按多对多关系排序?