尝试使用ajax与select2时出现错误

getting error when trying to use ajax with select2

本文关键字:错误 select2 ajax      更新时间:2023-09-26

知道如何调试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

任何想法的根本原因可能是什么或如何调试?

在后端代码中,请将查询更改为使用"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);

Credit go to -> Select2.js错误:Cannot read property 'length'未定义的