[英]Dynamic select2 options using api
I'll try to explain my problem as much as I can. 我会尽力解释我的问题。 I am trying to create, with
select2
plugin, a way for the user to write some letters and on each letter pressed a call to an API that gives the first 20 results given by that API. 我试图用
select2
插件创建一种方法,供用户写一些字母,并在每个字母上按下调用API,给出该API给出的前20个结果。
So I have my HTML select : 所以我选择了我的HTML:
<select name="filtre_products[]" class="form-control products-select2" multiple>
</select>
And then my JS (it's commented) : 然后我的JS(它的评论):
$(".products-select2").select2({
width: '100%',
closeOnSelect: false,
placeholder: '',
minimumInputLength: 3,
query: function (query) {
var data = {results: []}, i, j, s;
if(query.term != null) {
var ajax_r = [];
$.ajax({
url: 'ajax_products_recherche.php?limite=10&real_json=1&recherche='+query.term,
success: function(data_a){
//Getting the data
data_a = JSON.parse(data_a);
//Looping through the each data and putting them inside a table
data_a.forEach( (e) => {
ajax_r.push(e);
});
//Filtering the data to get from it the id and the text to be used
ajax_r.forEach( (e) => {
var tmp = e.split('-');
var id = tmp[0];
var name = tmp[2];
data.results.push({value: id, text: name});
});
query.callback(data);
}
});
}
},
//Sending the results to the function to modify the options as I please
templateResult: formatResult
});
And this is the formatResult
function I use : 这是我使用的
formatResult
函数:
function formatResult(d) {
if(d.loading) {
return d.text;
}
// Creating an option of each id and text
$d = $('<option/>').attr({ 'value': d.value }).text(d.text);
return $d;
}
My problem is that select2
is supposed to be creating the options dynamically upon initialization and thus actually creating <li>
out of the options and adding to them dynamically id's and such. 我的问题是
select2
应该在初始化时动态创建选项,从而实际创建选项中的<li>
并动态添加id等。 But in the way I'm creating it, it's putting the options INSIDE the <li>
tags which is not what I want, I want it to treat it as dynamic options like he does without the query call. 但是在我创建它的方式中,它将选项置于
<li>
标签内,这不是我想要的,我希望它将它视为动态选项,就像没有查询调用一样。
Some doc sources for you guys, it shows a part of what I'm trying to do, but the example shows how to show results from what we write, I want it to show from the api upon each click, and of course having multiple select added : http://select2.github.io/select2/#data 你们的一些文档资料来源,它显示了我正在尝试做的事情的一部分,但是这个例子显示了如何显示我们写的内容的结果,我希望它在每次点击时从api显示,当然还有多个选择添加: http : //select2.github.io/select2/#data
For your ajax success call, do this or similar. 对于您的ajax成功通话,请执行此操作或类似操作。 i think you don't require such big code.
我认为你不需要这么大的代码。 below code snippet is from my working script.
下面的代码片段来自我的工作脚本。
success: function (data) {
var dbSelect = $('#ddlItems'); // id for Dropdown list
dbSelect.empty();
result = JSON.parse(data);
// Parse result object and create your array collection in ajax_r object
for (var i = 0; i < ajax_r.length; i++) {
dbSelect.append($('<option/>', {
value: ajax_r.item[i].Value,
text: ajax_r.item[i].Text
}));
}
}
I've read the documentation and found that the ajax support seems to fit your needs. 我已阅读文档,发现ajax支持似乎符合您的需求。
In your select2 options object, add an ajax
object. 在select2选项对象中,添加一个
ajax
对象。 Inside this ajax
object : 在这个
ajax
对象里面:
results
array (just like the data object you're already building). results
数组的对象(就像你正在构建的数据对象一样)。 Then, you can reuse your templating function. 然后,您可以重复使用模板功能。
Here's a working snippet with a random API. 这是一个带有随机API的工作代码段。 Please note the query's term doesn't impact the returned data.
请注意查询的术语不会影响返回的数据。
$(document).ready(function () { $(".products-select2").select2({ width: '100%', closeOnSelect: false, placeholder: '', minimumInputLength: 3, ajax: { url: "https://jsonplaceholder.typicode.com/users", dataType: 'json', delay: 250, data: function (query) { // add any default query here return query; }, processResults: function (data) { // Tranforms the top-level key of the response object from 'items' to 'results' var results = []; data.forEach(e => { results.push({ id: e.id, text: e.name }); }); return { results: results }; }, }, templateResult: formatResult }); function formatResult(d) { if(d.loading) { return d.text; } // Creating an option of each id and text $d = $('<option/>').attr({ 'value': d.value }).text(d.text); return $d; } });
<html> <head> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.full.js"></script> </head> <body> <select name="filtre_products[]" class="form-control products-select2" multiple> </select> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.