您可以使用json_encode函数将任意数据转换为JSON。 假设您要返回一个字符串数组,以下是使用json_encode的方法:
include_once '../include/lib.php';
$res = array(); // initialize variables
$sqlgr = sprintf("
SELECT ACT_ID
FROM PRIVILLAGE
WHERE MAINGR_ID=%d
",
$_POST['gr_name']
); // only select those columns that you need
// and do not trust user input
$resultgr = sql($sqlgr);
while($rowgr = mysql_fetch_array($resultgr)){
$res[] = $rowgr['ACT_ID'];
}
echo json_encode($res); // use json_encode to convert the PHP array into a JSON object
// this will output something like ['foo', 'bar', 'blah', 'baz'] as a string
?>
在客户端,您可以使用jQuery.post方法 ,如下所示:
$("#group_name").change(function () {
$.post("selectedgr.php", {
gr_name: $(this).val()
}, function (data) {
// console.log(data);
// jQuery will convert the string "['foo', 'bar', 'blah', 'baz']" into a Javascript object
// (an array in this case) and pass as the first parameter
for(var i = 0; i $("#" + data[i]).attr("checked", "checked");
}
}, "json");
});