我正在尝试在select2中设置我预定义的选择选项 用ajax 但是当我使用ajax并点击select2时,它会删除之前我所拥有的html选项,任何想法如何让它保留选项,而不是删除它们直到我输入一些不相关的char?
我相信目前尚不清楚所以我对这两种情况进行了调整,以便您更好地理解
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();
答案 0 :(得分:-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);