如何通过Ajax请求使用带有JSON的Select2? [英] How to use Select2 with JSON via Ajax request?
问题描述
我的 Select2 3.4.5无法使用JSON数据。
My Select2 3.4.5 is not working with JSON data.
这是HTML上的输入框:
Here is my input box on HTML:
<input class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' />
...和我的JavaScript
…and my JavaScript
$(".itemSearch").select2({
placeholder: "Search for an Item",
minimumInputLength: 2,
ajax: {
url: "/api/productSearch",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
option: term
};
},
results: function (data, page) {
var more = (page * 10) < data.total;
return {
results: data.itemName,
more: more
};
}
},
formatResult: function (data, term) {
return data;
},
formatSelection: function (data) {
return data;
},
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) {
return m;
}
});
我使用Laravel 4创建了一个API,只要我在文本框中输入任何内容,就会返回一个值。
I made an API with Laravel 4 which returns a value whenever I type anything on my text box.
如果我在文本框中输入test,结果如下:
Here's the result if I type "test" on my text box:
[{"itemName":"Test item no. 1","id":5},
{"itemName":"Test item no. 2","id":6},
{"itemName":"Test item no. 3","id":7},
{"itemName":"Test item no. 4","id":8},
{"itemName":"Test item no. 5","id":9},
{"itemName":"Test item no. 6","id":10},
{"itemName":"Test item no. 7","id":11}]
我不能将结果添加到我的Select2下拉列表中。我认为 formatSelection
和 formatResult
导致了问题,因为我不知道应该在其上放置什么参数。我不知道从哪里获取容器,对象和查询等参数以及它应该返回的值,或者我的JSON响应是错误的?
I can't add the result to my Select2 dropdown. I think formatSelection
and formatResult
are causing the problem because I don't know what parameter should be placed on it. I don't know where to get those parameters like container, object and query and the values it should be returning, or is my JSON response is wrong?
推荐答案
这里有一个例子
$("#profiles-thread").select2({
minimumInputLength: 2,
tags: [],
ajax: {
url: URL,
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.completeName,
slug: item.slug,
id: item.id
}
})
};
}
}
});
这很容易
这篇关于如何通过Ajax请求使用带有JSON的Select2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!