获取复选框状态并通过布尔值将更改发布到数据库


get checkbox states and post changes to db by boolean value

我使用类似于下面的东西来输出(true/false)复选框,这些复选框通过数据库值表示特定计算机的设置。

div总是有一个唯一的ID值,前面加上代表计算机的"c"。复选框的每个设置都是1或0,表示真/假。下面的输出运行良好。现在,我想允许用户更改复选框,并通过"提交设置"链接将更改提交到数据库。请注意,页面上会有多个div(计算机),如下所示。

我想使用"提交设置"链接的jquery onclick来读取div id和三个设置的状态,然后做一个ajax帖子来更新数据库中的值。在一个完美的世界里,我想在点击后打开一个确认模式来确认更改,并提供一个选项,将这些设置用作特定帐户中所有计算机的默认设置。目前,我只是在寻找基本的,以后可能会扩展到这个。

我不知道从哪里开始使用jquery/ajax,因为这对我来说仍然是非常新的,但对于值发布到的php脚本不会有任何问题。

<div id="c'.$computer[computer_id].'">
    <label><input type="checkbox" '.($settings[hide_icon] == 1 ? 'checked' : 'unchecked').'> System tray icon?</label>
    <label><input type="checkbox" '.($settings['24h_format'] == 1 ? 'checked' : 'unchecked').'> 24 hour time format?</label>
    <label><input type="checkbox" '.($settings[stealth] == 1 ? 'checked' : 'unchecked').'> Stealth mode?</label>
    <label><a href="#">Submit settings</a></label>';
</div>

确保将div包装在表单中,并将名称添加到输入复选框中:

<form action="url_where_you_want_to_post" method="POST">
    <div id="c'.$computer[computer_id].'">
        <label><input name="hide_icon" type="checkbox" '.($settings[hide_icon] == 1 ? 'checked' : 'unchecked').'> System tray icon?</label>
        <label><input name="24h_format" type="checkbox" '.($settings['24h_format'] == 1 ? 'checked' : 'unchecked').'> 24 hour time format?</label>
        <label><input name="stealth" type="checkbox" '.($settings[stealth] == 1 ? 'checked' : 'unchecked').'> Stealth mode?</label>
        <label><a href="#" class="submit">Submit settings</a></label>';
    </div>
</form>
<script type="text/javascript">
    $(function () {
        $('.submit').on('click', function () {
            var $form = $(this).closest('form');
            $.ajax({
                type: $form.attr('method'),
                url: $form.attr('action'),
                data: $form.serialize()
            }).done(function (response) {
                // Depending on what you return from the server you can show some feedback for the user.
                // If you return lets say { success: true } from the server, then you can do:
                if (response.success) {
                    alert('Saved!');
                } else {
                    alert('Some error occurred.');
                }
            });
        });
    });
</script>