我从json数据
创建了一个jstree$('#tree-container').jstree({
'core': {
'data': {
'url': 'permission.php',
'data': function(node) {
return {'id': node.id};
},
"dataType": "json"
},
'themes': {
'responsive': true,
'icons': true
},
'checkbox': {
"keep_selected_style": false
}
},
'plugins': ['state', 'contextmenu','checkbox']
});
如何从我使用ajax和json从数据库获取的值中选中复选框?
答案 0 :(得分:0)
我发现了一种非常简单易行的方法,可以在jstree加载时显示“已检查”复选框(根据存储在数据库中的用户选择)。
Front end code:
<script>
$(document).ready(function(){
var ajaxResponse = '';
$.ajax({
url : 'response.php',
async : false,
success : function(response)
{
ajaxResponse = response;
}
});
var tree = $("#container");
tree.html(ajaxResponse);
tree.jstree({
plugins: ["checkbox" ], //["wholerow", "checkbox", "json_data", "ui", "themes"]
'checkbox': {
three_state: false,
cascade: 'up'
}
});
tree.jstree(true).open_all();
$('li[data-checkstate="checked"]').each(function() {
tree.jstree('check_node', $(this));
});
tree.jstree(true).close_all();
});
</script>
<head>
<meta charset="utf-8" />
<title>JsTree test</title>
<link rel="stylesheet" href="http://static.jstree.com/latest/assets/dist/themes/default/style.min.css" />
<script src="http://static.jstree.com/latest/assets/dist/libs/jquery.js"></script>
<script src="http://static.jstree.com/latest/assets/dist/jstree.min.js"></script>
</head>
<body>
<div id="container"/>
</body>
</html>
$getParentNodes = "select id, name from permissions where inherit_id IS NULL";
$resParentNodes = mysqli_query($conn, $getParentNodes);
$response = '';
if(mysqli_num_rows($resParentNodes) > 0)
{
while($parentNode = mysqli_fetch_assoc($resParentNodes))
{
$response .= '<ul><li data-checkstate="unchecked">'.$parentNode['name'];
$getChildNodes = "select id, name from permissions where inherit_id = '".$parentNode['id']."'";
$resChildNodes = mysqli_query($conn, $getChildNodes);
if(mysqli_num_rows($resChildNodes) > 0)
{
$response .= '<ul>';
while($childNode = mysqli_fetch_assoc($resChildNodes))
{
$checked = 'data-checkstate="unchecked"';
if($childNode['id'] == 5 || $childNode['id'] == 10 || $childNode['id'] == 11)
{
$checked = 'data-checkstate="checked"';
}
$response .= '<li '.$checked.'>'.$childNode['name'].'</li>';
}
$response .= '</ul>';
}
$response .= '</li></ul>';
}
}
echo $response;
This will show the checkbox checked with "data-checkstate="checked"