尝试在select2中使用ajax时出错

时间:2016-11-11 02:48:08

标签: javascript jquery select2

知道如何调试select2的ajax功能吗?以下是我正在尝试实施的示例:https://jsbin.com/sohupoviko/edit?html,output和 这是http://localhost:4000/users的结果集:

[
  {
    "id": 1,
    "first_name": "John",
    "last_name": "Smith"
  },
  {
    "id": 2,
    "first_name": "John2",
    "last_name": "Smith2"
  }
]

这是我在本地运行代码时返回的本地错误:

jquery.min.js:2 jQuery.Deferred exception: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefined
    at d (https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js:2:5214)
    at Object.f.transport.d.status.0.d.status.e.trigger.message (https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js:2:4227)
    at j (http://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:29948)
    at k (http://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:30262) undefined

知道根本原因是什么或如何调试?

1 个答案:

答案 0 :(得分:0)

在您的BackEnd代码中,请更改您的查询以使用" AS TEXT"

示例:

$query = $mysqli->query("SELECT id, first_name, last_name AS text FROM users WHERE fist_name LIKE '%$term%'"));
while ($row = mysql_fetch_assoc($query)) {
       $return[] = $row;
     }

echo json_encode($return);

信用转到 - > Select2.js error: Cannot read property 'length' of undefined