gpt4 book ai didi

javascript - select2 在使用 ajax 时删除默认选项

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:48:28 24 4
gpt4 key购买 nike

我正在尝试在 select2 中设置我预定义的选择选项与 Ajax 但是当我使用 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

最佳答案

在您处理用户发送的搜索查询的服务器端脚本中,返回应默认显示的前 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);

关于javascript - select2 在使用 ajax 时删除默认选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31005271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com