通过ajax一次多次更新

时间:2012-04-21 07:16:35

标签: php jquery ajax codeigniter

我只是想确保我现在正走在正确的轨道上:

制作一个小东西,以便管理员可以编辑人们的日程安排。现在他点击了一行,所有的时间表都变得可编辑。如果他连续改变了值,我就用

来捕捉它
$('.selector').change(function() { // this happens to be a <select> dropdown. I guess technically this is the <option> inside of the select.
    var updates = new Array(); // an array of all the updates
    var classList = $(this).attr('id').split(/\s+\); // the id of a <select> would be something like "12 monday start" meaning the user_id, day_of_week, start/end time. Just converting it to an array here.
    classList.push($(this).val()); // the time it has been changed to
    updates.push(classList); // add the singular time update to the overall array
    $('.save_schedule').click(function() {
        // here I would iterate through all of the arrays in updates and do some sort of ajax call, correct?
    });
});

只是想在我继续前进之前确保我走在正确的轨道上并且不得不重写一些东西。

由于

我的HTML已被请求:https://gist.github.com/2435293

2 个答案:

答案 0 :(得分:0)

如果您的HTML看起来像这样

<select id="12 monday start" class="selector">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<select id="12 monday end" class="selector">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<input type="button" class="save_schedule" value="save" />

你的javascript看起来像这样

$('.save_schedule').click(function() {

    var arr = new Array();
    $('.selector').each(function() {

        arr.push($(this).attr('id').split(/\s+/));
        arr.push($(":selected", this).val())
    });

    alert(arr);
    // ajax call here
});

see jsfiddle example

答案 1 :(得分:0)

我可以想到两种实现方法:

选项1 - 保存草案

每次用户编辑一行时,都会进行AJAX调用以临时保存更改(将数据库列draft添加到实际更改的不同草稿中)。

您应该将click处理程序移到change处理程序之外:

$('.selector').change(function() {
    ... 
});
$('.save_schedule').click(function() {
    ...
});

change处理程序中,$(this)指向当前标记select。 要获取所选值,您可以使用$(this).val()

为避免拆分select id属性以获取所需的所有元素,您可以使用自定义属性:

<select data-user-id="12" data-day="monday" data-time="start">...</select>

然后,在change处理程序中,您可以使用attr方法获取其值。

var user_id = $(this).attr('data-user-id');
var day = $(this).attr('data-day');
var time = $(this).attr('data-time');

现在,您可以进行ajax调用以将更改存储为draft

当用户点击save_schedule时,进行最后的ajax调用以更新草稿的状态并将其设置为永久。

选项2 - 简单保存,表格序列化

仅当用户点击“保存”按钮时,才会保存所有更改。

我建议将所有数据保存在HTML标记中而不是Javascript中。 (出于以下原因:如果用户编辑两次计划会发生什么?数组中的更改是否再次推送?)。

您可以隐藏输入/选择,因为它们不可编辑,您不再需要处理change事件。

当用户点击save_schedule时,您可以使用$(form).serialize()之类的功能从您的输入中收集所有数据(http://api.jquery.com/serialize/)并制作一个AJAX调用以保存您的更改。

相关问题