【问题标题】:put the dynamic data in dropdown list using select2.js使用 select2.js 将动态数据放在下拉列表中
【发布时间】:2018-06-19 06:03:37
【问题描述】:

我试图在 select2.js 中使用 ajax 从我的文件中获取数据。我想根据我在文本框中输入的值获取数据,并使用 select2 将该值附加到我的下拉列表中。我试过了,但它没有根据我的搜索关键字给出结果如何解决这些问题。

这是我的 HTML 输入框:

<input type="text" id="Address1" name="Address1" >

Javascript 代码

<script>    
$("#Address1").select2({
    tags: [],
    ajax: {
        url: 'ajaxhandler.php',
        dataType: 'json',
        type: "POST",
        // quietMillis: 50,
        data: function (term) {
            return {
                term: term
            };
        },
        results: function (term) {

        } 
    }
});
</script>

ajaxhandler.php

<?php
$CITIES = array("Ahmedabad", "Mumbai", "USA", "Canada", "Pune");
echo json_encode($CITIES); exit;
?>  

【问题讨论】:

    标签: html json jquery-select2


    【解决方案1】:

    Select2.js(第 4 版)的数据格式为:

    {
      "results": [
        {
          "id": 1,
          "text": "Option 1"
        },
        {
          "id": 2,
          "text": "Option 2"
        }
      ]
    }
    

    见:https://select2.org/data-sources/formats

    所以你需要processResults收到如下表单服务器:

        processResults: function (data) {
          return {
            results: $.map(data.items, function(obj, index) {
              return { id: index, text: obj };
            })
          };
        },
    

    这是一个小提琴:http://jsfiddle.net/beaver71/cwb9r23b/

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 2013-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-28
      相关资源
      最近更新 更多