如何在不取消复选框的情况下通过Ajax更新复选框列表

How can I update a list of checkboxes via Ajax without unchecking them

本文关键字:复选框 Ajax 列表 更新 情况下 取消      更新时间:2023-09-26

考虑以下复选框列表-联机用户列表和脱机用户列表;

<h1>Users</h1>
<div id="users">
<h2>Online</h2>
<ul>
        <li><input type="checkbox" name="userId[]" value="1" /> Joe Bloggs</li>
        <li><input type="checkbox" name="userId[]" value="2" /> Bill Gates</li>
        <li><input type="checkbox" name="userId[]" value="3" /> John Smith</li>
</ul>
<h2>Offline</h2>
<ul>
        <li><input type="checkbox" disabled="disabled" name="userId[]" value="4" /> The Queen</li>
        <li><input type="checkbox" disabled="disabled" name="userId[]" value="5" /> Steve Jobs</li> 
</ul>
</div>

用户可以检查在线用户,然后执行一项操作,例如向他们(1个或多个)发送电子邮件,但我需要在用户登录和退出系统时动态更新列表。

我每20秒左右更新一次列表的代码是这样的;

$("#users").load("/path/to/my/users/load.php");

但很明显,这只是替换了"users"div中的HTML,并取消选中用户选中的任何"online"框(如果用户还没有执行操作,这很烦人)。

简而言之;我正在努力在jQuery中编写必要的代码,这些代码可以获取在线和离线用户的列表,从列表中添加/删除他们,同时在"在线"列表中保持选中的值不变。

1)将列表包装成表格
2) 序列化所选复选框
3) 执行DOM替换
4) 遍历选定的复选框并重新应用

var checked = $('#users form').serializeArray();
//perform ajax call
//in the ajax success function after replacing the DOM
$.each(checked, function(i, data) {
  $('input[name="'+data.name+'"][value="'+data.value+'"]').attr('checked', 'checked');
});

采用不同的方法:使用.load(),比如$.getJSON()来检索一个看起来像的对象

{
    online: [
        {id: 1, name: 'Joe Bloggs'},
        {id: 2, name: 'Bill Gates'},
        {id: 3, name: 'John Smith'}
    ],
    offline: [
        {id: 4, name: 'The Queen'},
        {id: 5, name: 'Steve Jobs'}
    ]
}

并自己更新HTML,使用该用户ID的现有复选框(如果存在)。

当它们被更改时(onClick),您可以保存在全局var中,在.load之后,使用回调/其他方法重新检查它们。

使用ajax加载在线/离线用户,并根据其状态移动元素。我对此的看法:

// Define all users    
var allUsers = {users:[
            {id: 1, name: 'Joe Bloggs'},
            {id: 2, name: 'Bill Gates'},
            {id: 3, name: 'John Smith'},
            {id: 4, name: 'The Queen'},
            {id: 5, name: 'Steve Jobs'}
        ]
    };
    // Define which users are online
    var onlineUser = [2,3,5,12,76];

    $.each(allUsers.users,function(id,user){
        $('<input />').attr('type','checkbox').attr('name','userId[]').val(user.id).attr('disabled','disabled').appendTo($('<li />').text(user.name).appendTo($('#offline')));  
           });



    // function to update which users are online
    function reloadUsers(onlineUsers){
        $('#online li input').attr('disabled','disabled').parent().appendTo($('#offline'));
        $.each(onlineUsers, function(id,user){
            $('#offline [value="'+user+'"]').attr('disabled',false).parent().appendTo($('#online'));
        });
    }
// load online users on document load
reloadUsers(onlineUser);
// just used in the text example to show how to update online users
$("#reload").click(function(){
       reloadUsers($("textarea").val().split(","))
    });

示例:http://jsfiddle.net/niklasvh/4zde9/