我尝试用json文件中的数据填充选择表单。
[{"matricola":"1", "nome":"aaaaa"},{"matricola":"2", "nome":"bbbbbb"}]
如果我使用select可以正常工作,如果我尝试使用selectpicker,我不明白我必须在JavaScript代码中刷新selectpicker的位置。
这是我的代码:
<div class="form-group ">
<select id="cf" class="selectpicker show-tick form-control" data-dropup-auto="false" data-live-search="true" required="" name="cf">
</select>
</div>
<script>
let dropdown = document.getElementById('cf');
dropdown.length = 0;
let defaultOption = document.createElement('option');
defaultOption.text = 'Seleziona un dipendente';
dropdown.add(defaultOption);
dropdown.selectedIndex = 0;
const url = 'tables/griglia_dipendenti_incarichi.php';
const request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status === 200) {
const data = JSON.parse(request.responseText);
let option;
for (let i = 0; i < data.length; i++) {
option = document.createElement('option');
option.text = data[i].nome;
option.value = data[i].matricola;
if (i==0){
alert(option.text);
}
dropdown.add(option);
}
} else {
// Reached the server, but it returned an error
}
}
request.onerror = function() {
console.error('An error occurred fetching the JSON from ' + url);
};
request.send();
</script>
我尝试过
dropdown.add(option).selectpicker('refresh');
但没有用
答案 0 :(得分:1)
首先,您应该阅读本指南-https://developer.snapappointments.com/bootstrap-select/,并检查是否已将所有需要的文件链接到页面。
接下来是初始化Bootstrap-select插件。您可以对页面上的所有选择标签执行此操作:
$('select').selectpicker();
或仅针对您的元素:
$('#cf').selectpicker();
现在,如果您更改任何选择并希望用户看到更改,则需要刷新selectpicker插件。
如果您使用新版本的Bootstrap-select插件,请尝试以下操作:
$('#cf').selectpicker('refresh');
否则使用此:
$('#cf').selectpicker('destroy');
$('#cf').selectpicker();
附:这是一个简单的例子-https://jsfiddle.net/Denisdude/pf7qreum/17/
答案 1 :(得分:0)
非常感谢。它适用于假数据,而不适用于在线json
这是我的JavaScript代码:
<script>
$('#cf').selectpicker();
var Request = function () {
let dropdown = document.getElementById('cf');
dropdown.length = 0;
let defaultOption = document.createElement('option');
defaultOption.text = 'Seleziona un dipendente';
dropdown.add(defaultOption);
dropdown.selectedIndex = 0;
// data
const url = 'tables/griglia_dipendenti_incarichi.php';
const request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status === 200) {
const data = JSON.parse(request.responseText);
for (let i = 0; i < data.length; i++) {
let option;
option = document.createElement('option');
option.text = data[i].nome;
option.value = data[i].matricola;
/*if (i==0){
alert(option.text);
}*/
dropdown.add(option);
}
} else {
// Reached the server, but it returned an error
}
}
request.onerror = function() {
console.error('An error occurred fetching the JSON from ' + url);
};
request.send();
//alert('request has been sent!');
// here we refresh selectpicker plugin
//$('#cf').selectpicker('refresh');
// OR destroy and initialize it IF "refresh" didn't work
$('#cf').selectpicker('destroy');
$('#cf').selectpicker();
};
Request();
</script>
我最后的错误在哪里?