未捕获的TypeError:无法读取未定义的JQUERY自动完成的属性“长度”

时间:2015-04-27 16:26:55

标签: javascript jquery json autocomplete

使用此脚本, https://www.devbridge.com/sourcery/components/jquery-autocomplete/

我正在使用jQuery Autocomplete从我的数据库中搜索用户。

下面是返回Json的控制器:

public function searchusers1() {
    if ($_GET) {
        $query = $this -> input -> get('query');

        $searcharray = $this -> model_usermanage -> searchuser($query);

        $a_json = array();
        $a_json_row = array();
        foreach($searcharray as $row) {
            //$user_firstname = htmlentities(stripslashes($row['user_firstname']));
            //$user_lastname = htmlentities(stripslashes($row['user_lastname']));
            $user_email = htmlentities(stripslashes($row['user_email']));
            //$a_json_row["user_firstname"] = $user_firstname;
            $a_json_row["user_email"] = $user_email;

            array_push($a_json, $a_json_row);
        }
        echo json_encode($a_json);
    }
}

以下是我的jQuery:

$('#reply_bcc').autocomplete({
    serviceUrl: '<?php echo base_url(); ?>index.php/hi/test/searchusers1',
    minChars: 3,
    onSelect: function (suggestion) {
        console.log('You selected: ' + suggestion.data + ', ' + suggestion.data);
    }
});

这是我的JSON回复:

[{"user_email":"hi@test.com"},{"user_email":"hello@au.com"},{"user_email":"testing@123.com"},]

我的HTML:

<div class="col-md-10">
    <input type="text" name="reply_bcc" id="reply_bcc" autocomplete="off" class="form-control">
</div>

我的问题是:

我在控制台中出现以下错误,我无法在html输入中看到此搜索值作为下拉列表:

  

未捕获的TypeError:无法读取未定义的属性“长度”

这有什么问题?

谢谢!

2 个答案:

答案 0 :(得分:4)

文档说明“来自服务器的响应必须是遵循JavaScript对象的JSON格式:”

{
    // Query is not required as of version 1.2.5
    "query": "Unit",
    "suggestions": [
        { "value": "United Arab Emirates", "data": "AE" },
        { "value": "United Kingdom",       "data": "UK" },
        { "value": "United States",        "data": "US" }
    ]
}

你只是返回一个没有格式值/数据的数组。您可以在PHP中更改格式或使用“transformResult”函数为您的数组创建advice属性。

您应该在PHP代码中添加一个对象:

$obj = new stdClass();
$obj->suggestions = $a_json;
echo json_encode($obj);

答案 1 :(得分:0)

您不需要调用stdClass()。函数json_encode()为您将关联数组转换为JSON。这是一个示例:

<?php
$query="";
if (isset($_GET['query'])) $query=$db_handler->real_escape_string($_GET['query']);

$sql="SELECT `user_id`,`user_name` FROM `some_table`
    WHERE `user_name` LIKE '%{$query}%' ORDER BY `user_name`";
$res=$db_handler->query($sql);

if ($res->num_rows > 0)
{
    $data=array();
    while($row = $res->fetch_object())
    {
        $data[]=array("value" => $row->user_name, "data" => $row->user_id);
    }
    $res->free();
}
header('Content-Type: application/json');
echo json_encode(array("suggestions" => $data));
?>

上面的代码将输出如下内容:

{"suggestions":[{"value":"Joe Blow","data":"1000"},{"value":"Jane Blow","data":"1001"}]}

这是.autocomplete期望的格式:JavaScript对象表示法。