我是一名新手,尝试使用JQuery自动完成插件。但我无法在console.log
和alert
中获得结果,但无法通过自动完成建议获得结果。但不在建议列表中。
输入字段
'Name: <input type="text" id="hint" name="hint" />'
jquery
$(document).ready(function () {
$("#hint").keyup(function () {
$( "#hint" ).autocomplete({
source: function(request, response) {
//console.info(request, 'request');
//console.info(response, 'response');
$.ajax({
//q: request.term,
url: "<?php echo base_url(); ?>index.php?Librarian/autocomplete/",
data: { term: $("#hint").val()},
dataType: "json",
type: "POST",
success: function(data) {
alert(data)
console.log(data);
response(data);
}
});
},
minLength: 2
});
});
});
控制器
function autocomplete($param1 = '', $param2 = '', $param3 = '') {
// load model
$this->load->model("Librarian_model");
$search_data = $this->input->post('term');
$result = $this->Librarian_model->get_autocomplete($search_data);
echo json_encode($result);
//returning the result as result_array() also tried implode function but got the error at response
}
输出在控制台日志中: enter image description here
在警报中,我得到了object-object,但是当我使用JSON.stringify时,输出是一个数组
答案 0 :(得分:0)
表明您是ajax响应格式问题的接缝,使用map
函数格式化ajax响应-
$(document).ready(function () {
$("#hint").keyup(function () {
$( "#hint" ).autocomplete({
source: function(request, response) {
//console.info(request, 'request');
//console.info(response, 'response');
$.ajax({
//q: request.term,
url: "<?php echo base_url(); ?>index.php?Librarian/autocomplete/",
data: { term: $("#hint").val()},
dataType: "json",
type: "POST",
success: function(data) {
alert(data)
console.log(data);
response($.map(data, function (item) {
return {
label: item.name,
value: item.name
};
}));
}
});
},
minLength: 2
});
});
});