将复选框字段存入数据库
问题描述:
Currently, the checkbox field in the database is stored as ["B"],["C"]. I was wondering if there is anyway possible way to store the checkbox field as BC only.
$(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
答
Since it looks like you're passing the value of role
directly into the database, rather than using JSON.stringify
to create role
, you could just use Array.join
method:
var checklist = ['B', 'C'];
var role = checklist.join('');
console.log(role);
console.log(JSON.stringify(checklist));
</div>
答
Yes.
Currently you are using JSON.stringify on an array of elements which will give you "["B"],["C"]".
Try using join for an example to make a string of the array before stringify it:
role = JSON.stringify(checklist.join(""));
Output:
"BC"
Regards Daniel.