我正在使用jQuery select2插件并尝试通过Ajax请求显示数据。但它没有调用Ajax函数,我已经尝试了所有东西,但没有工作。这是我的代码 -
HTML
<select class="form-control " multiple="" data-placeholder="Select Youtube Videos" aria-hidden="true" name="collection_youtube_videos[]" id="collection_youtube_videos"></select>
javascipt的
$(document).ready(function(){
$('#collection_youtube_videos').select2({
ajax: {
url: url,
dataType: 'json',
data: function (params) {
var query = {
//trim the extra whitespace
search: params.term.replace(/\s+/g, " ").trim(),
}
// Query parameters will be ?search=[term]&type=public
return query;
},
processResults: function (data) {
// Transforms the top-level key of the response object from 'items' to 'results'
return {
results: data.items
};
}
}
});
});
我正在使用以下版本
JQuery - 2.1.4
选择2 - 4.0.0
问题是当我在select2的输入框中输入内容时,它没有调用此ajax请求来获取数据。任何人都可以帮我这个吗?
答案 0 :(得分:1)
您可以按照以下
更改ajax电话选中此链接以供参考,其中包含类似问题https://stackoverflow.com/a/21602199/6429700
$(document).ready(function(){
var url = "test.php";
$('#collection_youtube_videos').select2({
minimumInputLength: 2,
tags: [],
ajax: {
url: url,
dataType: 'json',
data: function (params) {
var query = {
//trim the extra whitespace
search: params.term.replace(/\s+/g, " ").trim(),
}
// Query parameters will be ?search=[term]&type=public
return query;
},
processResults: function (data) {
// Transforms the top-level key of the response object from 'items' to 'results'
return {
results: data.items
};
}
}
});
});
&#13;
select {
width: 200px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.min.js"></script>
<select class="form-control " multiple="" data-placeholder="Select Youtube Videos" aria-hidden="true" name="collection_youtube_videos[]" id="collection_youtube_videos"></select>
&#13;
答案 1 :(得分:0)
你必须添加“select2”css类来选择标签
<select class="form-control select2" multiple="" data-placeholder="Select Youtube Videos" aria-hidden="true" name="collection_youtube_videos[]" id="collection_youtube_videos"></select>