我正在尝试将 Select2 设置为使用 Ajax 并且被卡住了。我已经在 IE 中调试并确认我的 AJAX 正在返回结果,所以这似乎不是问题。输入框加载,但是当我在“牛奶”中输入“mi”时,它只是说“正在搜索......”并且什么也没找到!
这是我的jQuery:
$(document).ready(function () {
$('#e1').select2({
placeholder: "Select an ingredient...",
minimumInputLength: 2,
ajax: {
url: "../api/IngredientChoices",
dataType: "jsonp",
quietMillis: 500,
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page
};
},
results: function (data, page) {
var more = (page * 10) < data.total;
return {
results: data.MainName, more:more
}
}
}
});
});
JSON:
[{"SubItemID":1,"MainItemID":1,"SubName":"2%","MainName":"Milk"},{"SubItemID":2,"MainItemID":1,"SubName":"Skim/Fat Free","MainName":"Milk"},{"SubItemID":3,"MainItemID":2,"SubName":"Chedder","MainName":"Cheese"}]
HTML:
<td><input type="hidden" id="e1" /></td>
如果我将 dataType 更改为只是 json,当我在框中键入“mi”时会出现另一种错误。
这是工作版本的最终代码:
$('#e1').select2({
placeholder: "Select an ingredient...",
minimumInputLength: 2,
ajax: {
url: "../api/IngredientChoices",
dataType: "json",
quietMillis: 500,
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page
};
},
results: function (data, page) {
var more = (page * 10) < data.length;
console.log(more);
console.log(data);
return { results: data, more: more };
},
formatResult: function (post) {
markup = '<strong>' + post.text + '</strong>';
}
}
});