html - 使用 select2.js 将动态数据放入下拉列表中

标签 html json jquery-select2

我尝试使用 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;
?>  

最佳答案

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 };
        })
      };
    },

这是一个 fiddle :http://jsfiddle.net/beaver71/cwb9r23b/

关于html - 使用 select2.js 将动态数据放入下拉列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48181139/

相关文章:

javascript - 单击时在 Select2 多选上指定边框颜色

div 大小调整或其他方面的 jQuery 冲突?

javascript - JQuery 容器操作

javascript - 如何使用 ExtJS 4 读取嵌套的 json 文件

java - 如何为 Android 中最后插入的记录设置颜色?

javascript - 如何在 Select2 插件中禁用选项?

jquery - 取消选中 radio

javascript - $ ("#id").val() 与 document.getElementById ("id").value 的工作方式不同

javascript - 如何将外部 JSON 文件读入我的 html/javascript 测验

javascript - Select2 下拉菜单允许用户在用户键入时输入新值