如何将jstree复选框值插入数据库
Posted
技术标签:
【中文标题】如何将jstree复选框值插入数据库【英文标题】:How to insert jstree checkbox value into database 【发布时间】:2017-02-27 12:36:25 【问题描述】:<script type="text/javascript">
$(document).ready(function()
//fill data to tree with AJAX call
$('#tree-container').jstree(
'plugins': ["wholerow", "checkbox"],
'core' :
'data' :
"url" : "response.php",
"dataType" : "json" // needed only if you do not supply JSON headers
)
);
</script>
<div id="tree-container"></div>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "defectsystem";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* check connection */
if (mysqli_connect_errno())
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
$sql = "SELECT * FROM `treeview_items` ";
$res = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_assoc($res) )
$data[] = $row;
$itemsByReference = array();
// Build array of item references:
foreach($data as $key => &$item)
$itemsByReference[$item['id']] = &$item;
// Children array:
$itemsByReference[$item['id']]['children'] = array();
// Empty data class (so that json_encode adds "data: " )
$itemsByReference[$item['id']]['data'] = new StdClass();
// Set items as children of the relevant parent item.
foreach($data as $key => &$item)
if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
$itemsByReference [$item['parent_id']]['children'][] = &$item;
// Remove items that were added to parents elsewhere:
foreach($data as $key => &$item)
if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
unset($data[$key]);
// Encode:
echo json_encode($data);
?>
我已经成功地创建了一个带有复选框的 jstree。但是,当我单击它并提交时,如何将复选框值插入数据库。
如果有人可以帮助我,谢谢!如果有任何问题可以在下面的评论中问我。
【问题讨论】:
【参考方案1】:试试这样的:
var array = [];
// create an array
$.each($("input[name='user_permission']:checked"), function()
permissions.push($(this).val());
);
// Iterate over each checkbox which is checked and push its value in the array variable.
例如:
......
var permissions = [];
$.each($("input[name='user_permission']:checked"), function()
permissions.push($(this).val());
);
$.ajax(
url : 'add_permission.php',
method : 'post',
data :
permissions : JSON.stringify(permissions)
....
);
// After complete iteration you will get the value of each checked checkbox.
现在使用 ajax 调用将其插入数据库
【讨论】:
是的,我找到了很多类似的编码。 我在我的项目中使用它,它就像一个魅力 例如 function submitMe() var checked_ids = []; $('#your-tree-id').jstree('get_checked',null,true).each(function() checked_ids.push(this.id); ); //设置为隐藏字段 document.getElementById('jsfields').value = checked_ids.join(","); 我明白了,你能详细解释一下吗? 谢谢!还有一个问题。我在我的 jstree 中有三个级别。例如,公司是 1 级,项目是 2 级,阶段是 3 级。我想将其插入到包含 3 列的表中。我该怎么做?以上是关于如何将jstree复选框值插入数据库的主要内容,如果未能解决你的问题,请参考以下文章
如何将 SELECT ALL 值或 SELECTED 复选框值插入 mysql 中的不同列?