【问题标题】:getting error when trying to use ajax with select2尝试将 ajax 与 select2 一起使用时出错
【发布时间】:2016-11-11 02:48:07
【问题描述】:

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

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

【问题讨论】:

    标签: javascript jquery select2


    【解决方案1】:

    在您的后端代码中,请更改您的查询以使用 "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

    【讨论】:

    • 我的后端不同。这是一个简单的 db.json 文件,带有一些硬编码的 json 对象。 json-server 将文件信息作为 json 返回。我确保所有属性名称和值都包含在引号中但这并不能解决问题。是否可以对结果对象执行某种类型的附加例程,例如 JSON.stringify() 或拆分 select2 处理函数以解决此错误? s
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 2019-08-24
    • 2012-10-30
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多