【问题标题】:storing checkbox field into database将复选框字段存储到数据库中
【发布时间】:2018-12-05 06:21:54
【问题描述】:

目前,数据库中的复选框字段存储为 ["B"],["C"]。我想知道是否有可能将复选框字段存储为仅 BC。

$(document).ready(function() {
    "use strict";

    var role;
});

function savenewuser() {
    var url = serverURL() + "/newadmin.php";
    checklist = new Array();
    $('input:checkbox[name="roles[]"]:checked').each(function() {
        checklist.push($(this).val());
    });

    role = JSON.stringify(checklist);

    $.ajax({
        url: url,
        type: 'GET',
        data: {
            "role": role,
        },
        success: function(arr) {
            _getNewUserResult(arr);
        },
        error: function() {
            alert("error");
        }
    });
}

<div><label for="rights">Rights</label></div>
<input type="checkbox" name="roles[]" value="A">Bookings
<input type="checkbox" name="roles[]" value="B">Incident Booking
<input type="checkbox" name="roles[]" value="C">Edit User

【问题讨论】:

  • 你的php代码是什么?
  • 您寻求的答案完全取决于您的数据库架构和您的 php 脚本。您发布的 JavaScript 很有趣,但最终并不重要。

标签: javascript php html database


【解决方案1】:

由于您似乎将role 的值直接传递到数据库中,而不是使用JSON.stringify 创建role,因此您可以只使用Array.join 方法:

var checklist = ['B', 'C'];
var role = checklist.join('');
console.log(role);
console.log(JSON.stringify(checklist));

【讨论】:

    【解决方案2】:

    是的。

    目前您在一个元素数组上使用 JSON.stringify,这将为您提供 "["B"],["C"]"。

    尝试使用 join 示例在字符串化之前制作数组的字符串:

    role = JSON.stringify(checklist.join(""));
    

    输出:

    "BC"
    

    问候丹尼尔。

    【讨论】:

      猜你喜欢
      • 2013-02-20
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      • 1970-01-01
      • 2015-04-17
      • 1970-01-01
      • 2013-04-13
      相关资源
      最近更新 更多