如此简单的设置 jQuery 自动完成对我来说不起作用,为什么我对此感到奇怪,你能检查一下这有什么问题吗?
Jquery Function
$("#location_suggetion").autocomplete({
autoFocus: true,
minLength: 1,
source: function(request,response) {
$.ajax ({
url: base_url+'data_check/get_location',
data: {term: request.term},
dataType: "jsonp",
cache: false,
success: function(data) {
response( $.map( data.suggestions, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
});
PHP File Code
$term = $this->input->get('term');
$query = $this->db->query('SELECT * FROM `tb_cities` WHERE name LIKE "'.$term.'%" LIMIT 0,6');
$results = $query->result();
$html = '';
$html.= '[';
foreach($results as $result){
$html.= '{ label: "'.$result->name.', '.get_country_row($result->country_id)->name.'", value: "'.$result->name.'" },';
}
$html.='];';
echo $html;
Console Get me Result
[{ label: "Rangat, India", value: "Rangat" },{ label: "Rajahmundry, India", value: "Rajahmundry" },{ label: "Rajamahendri, India", value: "Rajamahendri" },{ label: "Rajampet, India", value: "Rajampet" },{ label: "Rajendranagar, India", value: "Rajendranagar" },{ label: "Rajoli, India", value: "Rajoli" },];
最佳答案
jsonp
用于跨域
请求。使用 json
代替。您在控制台中的 JSON 日期错误检查 here 。要将数组转换为 JSON 字符串,请使用 json_encode。将您的 php 代码更改为:
$term = $this->input->get('term');
$query = $this->db->query('SELECT * FROM `tb_cities` WHERE name LIKE "'.$term.'%" LIMIT 0,6');
$results = $query->result();
$html= array();$i=0;
foreach($results as $result){
$html[$i]['label']=$result->name.', '.get_country_row($result->country_id)->name;
$html[$i]['value']=$result->name;
$i++;
}
echo json_encode($html);
可以直接使用,不需要在jquery部分进行转换,因为结构已经匹配。
关于javascript - jQuery 自动完成与 Ajax 建议不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41544039/