【问题标题】:select2 removes default options when using ajaxselect2 使用 ajax 时删除默认选项
【发布时间】:2015-09-09 09:34:50
【问题描述】:

我正在尝试在select2 中设置我的预定义选择选项 用阿贾克斯 但是当我使用 ajax 并单击 select2 时,它会删除我之前在那里的 html 选项,知道如何让它保持原样而不删除它们,直到我输入一些不相关的字符?

我认为这还不清楚,所以我对这两种情况都做了一些调整,以便您更好地理解

HTML

<select id="e1" style="width:300px">
        <option value="AL">Alabama</option>
        <option value="Am">Amalapuram</option>
        <option value="An">Anakapalli</option>
        <option value="Ak">Akkayapalem</option>
        <option value="WY">Wyoming</option>
    </select>


<select id="e2" style="width:300px">
        <option value="AL">Alabama</option>
        <option value="Am">Amalapuram</option>
        <option value="An">Anakapalli</option>
        <option value="Ak">Akkayapalem</option>
        <option value="WY">Wyoming</option>
    </select>

js

$("#e1").select2({ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    processResults: function (data, page) {
      // parse the results into the format expected by Select2.
      // since we are using custom formatting functions we do not need to
      // alter the remote JSON data
      return {
        results: data.items
      };
    },
    cache: true
  }});

$("#e2").select2();

fiddle example of select2 ajax and none ajax

【问题讨论】:

标签: javascript ajax jquery-select2 jquery-select2-4


【解决方案1】:

在您正在处理用户发送的搜索查询的服务器端脚本中,返回应默认显示的前 5 个元素,即使查询为空。

 $query=$_REQUEST['q'];
 if (!empty($query)) {
     //populate the results if the user is typed something in
 } else {
   $results=array();
   $results[0]['text']=Alabama;
   $results[0]['id']="idofalabama";
   // and so on, for the number of results you want to display when the user didn't input anything in the search box
 }
 return json_encode($results);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    相关资源
    最近更新 更多