将参数传递给 jQuery 的 select2 ajax 调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13637841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
passing parameters to jQuery's select2 ajax call
提问by Cary
I'm attempting to pass an extra parameter to an ajax call within select2:
我试图将一个额外的参数传递给 select2 中的 ajax 调用:
$(".auto-sug").select2({
width:'element',
minimumInputLength:2,
ajax: {
url: "/action/get-custom.php",
data: function (term, page) {
return {
q: term, // search term
page_limit: 10
};
},
results: function (data, page) {
return {results: data.stuff};
}
}
});
I actually want to pass another parameter to the ajax call... the id of the element itself
我实际上想将另一个参数传递给 ajax 调用...元素本身的 id
<input type="text" class="auto-sug" name="custom" id="3383" />
however, I'm unable to figure out how to actually access the id of the element (3383) or any other value on the page.
但是,我无法弄清楚如何实际访问元素的 id (3383) 或页面上的任何其他值。
采纳答案by sjy
Assuming there are multiple elements with class auto-sug
, you could try something like this:
假设 class 有多个元素auto-sug
,您可以尝试以下操作:
$(".auto-sug").each(function() {
var thisId = this.id;
$(this).select2({
...
ajax: {
...
id: thisId,
},
});
});
回答by Sergio
You should pass that extra parameter inside the data function instead of the root ajax, for it to execute each time you make a request:
您应该在数据函数而不是根 ajax 中传递该额外参数,以便在每次发出请求时执行:
ajax: {
url: "/action/get-custom.php",
data: function (term, page) {
return {
q: term, // search term
anotherParm: whatEverValue, //Get your value from other elements using Query, for example.
page_limit: 10
};
Then for getting the id for the current select2 you could replace whateverValue
with $(this).data(key)
然后为了获取当前 select2 的 id,您可以替换whateverValue
为$(this).data(key)
回答by Maximiliano Cesán
You can add a new params here.
您可以在此处添加新参数。
data: function (params) {
ultimaConsulta = params.term;
localidad = $("#idOcultoLocalidad").val(); //this is the anotherParm
return {
criterio: params.term, // search term
criterio2: localidad,
};
},