javascript - jQuery 自动完成与 Ajax 建议不返回

标签 javascript php jquery ajax

如此简单的设置 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/

相关文章:

javascript - 删除时的 Angular ng-repeat 动画

javascript - 从一行字符串中提取价格的最佳方法是什么?

php - TCPDF 不同边的特定边框

php - 如何删除 MySQL 中的行表?

php - url 编码的奇怪问题

jquery - 文本区域中的字数始终返回 11

javascript - Jquery调整大小: how to check if a screen has been resized at any point

javascript - 使用 JavaScript 查询 SharePoint 列表

bool 数组计数的 JavaScript 性能

javascript - Spring Boot Ajax 动态填充选择选项