這是在我的項目的解決方案:
在edit.php文件:
溶液1(美食ID爲單數):
<?php
$cate_row = $db->fetchRow("SELECT cate_id, cate_name FROM categories WHERE cate_id=".$editdata[cate_id]." AND cate_status='Active'");
$cateArray[] = array("id"=>$cate_row['cate_id'], "text"=>$cate_row['cate_id']." - ".$cate_row['cate_name']);
echo "<script type=\"text/javascript\">
AjaxCombo('#categories', '/ajax/getCategories.php', true)
</script>";
echo "<input type=\"hidden\" name=\"sl2\" id=\"categories\" value='".json_encode($cateArray)."' data-placeholder=\"Select a category for this product..\" style=\"width: 400px !important;\" />";
?>
溶液2(美食id爲數組:12,4,5,6或,12,4,5,6,):
<?php
$cate_q = $db->query("SELECT cate_id, cate_name FROM categories WHERE cate_status='Active' ORDER BY cate_name ASC");
// array: ,12,4,5,6,
$editcate_array = explode(",", substr($editdata[cate_id], 1, $editdata[cate_id] - 1));
// or array 12,4,5,6
// $editcate_array = explode(",", $editdata[cate_id]);
while($cate_row = $db->fetch_array($cate_q)){
if(in_array($row['cate_id'], $editcate_array)) {
$cateArray[] = array("id"=>$cate_row['cate_id'], "text"=>$cate_row['cate_id']." - ".$cate_row['cate_name']);
}
}
echo "<script type=\"text/javascript\">
AjaxCombo('#categories', '/ajax/getCategories.php', true)
</script>";
echo "<input type=\"hidden\" name=\"sl2\" id=\"categories\" value='".json_encode($cateArray)."' data-placeholder=\"Select a category for this product..\" style=\"width: 400px !important;\" />";
?>
在JS global.js:
function AjaxCombo(elm, url, multiple) {
$(document).ready(function() {
$(elm).select2({
multiple: multiple,
minimumInputLength: 1,
ajax: {
url: url,
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return { q: term };
},
results: function (data, page) {
return {results: data};
}
},
// Add new category if no exist
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} }
});
$(elm).select2("data", JSON.parse($(elm).val()));
});
}
默認如果表單編輯含有數據select2 init「id - 名稱類別」。
文件getCategories.php:從選擇你$q = $input->gc['q']
和MySQL是cate_name LIKE '%" . $q . "%';
while($row = $db->fetch_array($result)){
$dataArray[] = array("id"=>$row['cate_id'], "text"=>$row['cate_id']." - ".$row['cate_name']);
}
header('Content-Type: application/json');
echo json_encode($answer);
時,你得到價值形態選擇2,你可以嘗試:
foreach ($_GET['select2'] as $value) {
echo $value;
}
完成!
謝謝約翰,這個作品非常完美,比聆聽變化和手動變換要乾淨得多。 – Toby 2014-12-12 05:45:07