gpt4 book ai didi

javascript - Select2 显示 ajax 请求错误

转载 作者:行者123 更新时间:2023-12-03 05:59:08 26 4
gpt4 key购买 nike

enter image description here 我想通过 ajax 请求将 select2 与数据一起使用。但它显示此错误

Error: Option 'ajax' is not allowed for Select2 when attached to a <select> element.

HTML

<select id='myselect' class='select2-input select2'>
<option></option>
<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

$(document).ready(function() {
var base_url = $('#baseurl').val();
$("#myselect").select2({
placeholder: "Select a State",
allowClear: true,
ajax: {
url: base_url + 'selecttest',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term.term
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.expense_detail,
id: item.user_id
}
})
};
}
}
});

像这样获取 JSON 响应

[{"expense_id":"2","user_id":"5","expense_detail":"abcdh1","amount":"123","expense_date":"2016-10-18","expense_type":"pocket","team_code":"0","team_id":"0"},{"expense_id":"3","user_id":"5","expense_detail":"hxyz1","amount":"123","expense_date":"2016-10-11","expense_type":"","team_code":"45664654","team_id":"46546"},{"expense_id":"4","user_id":"5","expense_detail":"abch2","amount":"123","expense_date":"2016-10-11","expense_type":"","team_code":"45664654","team_id":"46546"},{"expense_id":"5","user_id":"5","expense_detail":"abh3","amount":"123","expense_date":"2016-10-11","expense_type":"","team_code":"45664654","team_id":"46546"},{"expense_id":"6","user_id":"5","expense_detail":"ah4","amount":"123","expense_date":"2016-10-11","expense_type":"","team_code":"45664654","team_id":"46546"},{"expense_id":"7","user_id":"5","expense_detail":"h5","amount":"123","expense_date":"2016-10-11","expense_type":"","team_code":"45664654","team_id":"46546"}]

我正在使用此 select2 版本

版权所有 2012 伊戈尔·维恩伯格

版本:3.2 时间戳:2012 年 9 月 10 日星期一 10:38:04 PDT 2012

非常感谢任何帮助..谢谢。

最佳答案

Select2 期望结果带有 IDTEXT 属性,因此您需要将结果回调重写为,

            results: function (data) {
var tmpResults = [];

$.each(data, function (index, item) {
tmpResults.push({
'id': item.user_id,
'text': item.expense_detail,
});
});
return {
results: tmpResults
};
}

希望这有帮助

关于javascript - Select2 显示 ajax 请求错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39818937/

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