[英]Loading remote data only once with Select2
正如標題所暗示的,我只想加載一次遠程數據。 我想過使用獨立的 ajax 調用加載數據並在控件中“本地”設置它,但想知道是否有更多“內置”的方式來做到這一點......
可以在此處找到解決方案:
https://github.com/ivaynberg/select2/issues/110
$("#selIUT").select2({
cacheDataSource: [],
placeholder: "Please enter the name",
query: function(query) {
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData.result});
return;
} else {
$.ajax({
url: '/ajax/suggest/',
data: { q : query.term },
dataType: 'json',
type: 'GET',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data.result});
}
})
}
},
width: '250px',
formatResult: formatResult,
formatSelection: formatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
編輯:
我可能誤解了你的問題。 如果您希望一次加載所有數據,則使用 Select2,沒有內置功能可以做到這一點。
您建議執行單個查詢,然后在 Select2 中使用存儲的數據將是可行的方法。
這適用於 Select2 v4.0.3:
我有同樣的問題,並通過觸發 AJAX 調用並使用返回的數據作為初始化數據數組來解決它。
// I used an onClick event to fire the AJAX, but this can be attached to any event.
// Ensure ajax call is done *ONCE* with the "one" method.
$('#mySelect').one('click', function(e) {
// Text to let user know data is being loaded for long requests.
$('#mySelect option:eq(0)').text('Data is being loaded...');
$.ajax({
type: 'POST',
url: '/RetrieveDropdownOptions',
data: {}, // Any data that is needed to pass to the controller
dataType: 'json',
success: function(returnedData) {
// Clear the notification text of the option.
$('#mySelect option:eq(0)').text('');
// Initialize the Select2 with the data returned from the AJAX.
$('#mySelect').select2({ data: returnedData });
// Open the Select2.
$('#mySelect').select2('open');
}
});
// Blur the select to register the text change of the option.
$(this).blur();
});
這對我的想法很有效。 希望這可以幫助人們搜索相同的問題。
一次加載數據:
假設:
您在 /services 處有一個 REST API 端點,用於提供 JSON 對象數組
該數組包含至少具有“name”和“id”屬性的對象。 例子:
[{"id": 0, "name": "Foo"}, {"id": 1, "name": "Bar"}]
您想將該數組存儲為全局“services_raw”
首先,我們的函數加載數據並創建全局“services_raw”(又名“window.services_raw”):
fetchFromAPI = function() {
console.log("fetchFromAPI called");
var jqxhr = $.ajax(
{
dataType:'json',
type: 'GET',
url: "/services",
success: function(data, textStatus, jqXHR) {
services_raw = data;
console.log("rosetta.fn.fetchServicesFromAPI SUCCESS");
rosetta.fn.refreshServicesSelect();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error inside rosetta.fn.fetchServicesFromAPI", errorThrown, textStatus, jqXHR);
setTimeout(rosetta.fn.fetchServicesFromAPI(), 3000); // retry in 3 seconds
}
}
)
.done(function () {
console.log("success");
console.log(jqxhr);
})
.fail(function () {
console.log("error");
})
.always(function () {
console.log("complete");
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function () {
console.log("second complete");
});
};
其次,我們的 Select2 實例化代碼將我們的數據轉換為 Select2 可以使用的格式:
refreshServicesSelect = function () {
// ref: http://jsfiddle.net/RVnfn/2/
// ref2: http://jsfiddle.net/RVnfn/101/ # mine
// ref3: http://jsfiddle.net/RVnfn/102/ # also mine
console.log('refreshServicesSelect called');
$("#add-service-select-service").select2({
// allowClear: true
data: function() {
var arr = []; // container for the results we're returning to Select2 for display
for (var idx in services_raw) {
var item = services_raw[idx];
arr.push({
id: item.id,
text: item.name,
_raw: item // for convenience
});
}
return {results: arr};
}
});
};
在調用上述函數之前,HTML 中的 Select2 元素應如下所示:
<input id="add-service-select-service" type="hidden" style="width:100%">
要使用所有這些,請調用(在 JS 中):
window.fetchFromAPI();
window.refreshServicesSelect();
最后,這是一個 JSFiddle,您可以在其中玩類似的東西: http : //jsfiddle.net/RVnfn/102/
基本上,在我上面的示例中,我們只是使用 ajax 來填充 Fiddle 中的 window.pills 等效項。
希望這有幫助:)
如果您知道如何通過 Select2 .ajax 函數執行此操作,請回復,因為這會更短一些。
在我的情況下,它與給定的代碼完美配合
$('#itemid').select2({
cacheDataSource: [],
closeOnSelect: true,
minimumInputLength: 3,
placeholder: "Search Barcode / Name",
query: function(query) {
// console.log(query);
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData});
return;
} else {
$.ajax({
url: "./includes/getItemSelect2.php",
data: { value : query.term },
dataType: 'json',
type: 'POST',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data});
}
});
}
},
});
我從ajax返回的數據是這種形式
<?php
$arr = [
["id" => 1, "text" => "Testing"],
["id" => 2, "text" => "test2"],
["id" => 3, "text" => "test3"],
["id" => 4, "text" => "test4"],
["id" => 5, "text" => "test5"]
];
echo json_encode($arr);
exit();
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.