4

我正在尝试使用 ajax 在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();

select2 ajax 和无 ajax 的小提琴示例

4

1 回答 1

-2

在您正在处理用户发送的搜索查询的服务器端脚本中,返回应默认显示的前 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);
于 2015-10-17T02:47:31.810 回答