我使用boostrap typhead创建自动完成
我希望在自动填充中选择数据时显示, 返回2个值并放置到输入框和隐藏数据
我发现了2个问题
这是我的代码
PHP
<?php
include "database.php";
$query = $_REQUEST['query'];
$result = mysqli_fetch_object(mysqli_query($con,"select count(*) as total from biodata where NameBiodata LIKE '%".$query."%' "));
if ($result->total > 0) {
$data_tsk = mysqli_query($con,"select IdBio,NameBiodatafrom biodata where NoUrut NameBiodata LIKE '%".$query."%'");
$data = array();
while($tsk=mysqli_fetch_object($data_tsk)){
array_push($data,array('label'=>$tsk->NameBiodata,'value'=>$tsk->IdBio));
}
echo json_encode($data);
}
?>
的Javascript
$('#name_biodata').typeahead({
source: function (query, process) {
$.ajax({
url: 'ajax/auto_complete_biodata.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + $('#name_biodata').val(),
success: function(data) {
var results = data.map(function(item) {
var someItem = { myname: item.label, myvalue: item.value};
var jsonString = JSON.stringify(someItem.myname);
return jsonString; // I don't know how to remove double qoutes
//return jsonString.replace(/\"/g, ""); // I try to remove double qoutes, but not selected
});
return process(results);
}
});
},
minLength: 1,
updater: function(item) {
var obj = JSON.parse(item);
console.log(obj); // i can't get Id BIO :(
$("#IdBio").val(obj.value);
return item;
}
});
JSON
[{"label":"Yeni Adelia Sofiyah als Selvi","value":"151"},{"label":"Yenni Ginting als Kak Yen","value":"276"},{"label":"Ria Wira","value":"572"}]
帮助我谢谢
答案 0 :(得分:1)
双引号由JSON.stringify
引起。当您希望通过HTTP请求发送JSON,将JSON作为字符串回显等时,此方法很有用。在您的情况下,只需使用var jsonString = someItem.myname;
。
您的代码在这里通常是错误的。 source
应该如下所示
source: [
{name: "name", any: "value", you: "want"},
{name: "name2", any: "value", you: "want"}
];
name
字段是必需的。没有它,如果你想传递对象(具有名称和其他值)而不是单个值,则typeahead将无法工作。在你的情况下,你得到
source: ['one', 'two', 'three', 'etc'];
所以你应该做那样的事情
source: function (query, process) {
$.ajax({
url: 'ajax/auto_complete_biodata.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + $('#name_biodata').val(),
success: function(data) {
var results = data.map(function(item) {
var someItem = { name: item.label, myvalue: item.value};
return someItem;
});
return process(results);
}
});
},
现在你会得到
[
{name: 'name_from_label', myvalue: 'your_value'}
]
这就是全部。