我有一个Rails应用程序,并且正在使用Stimulus根据表单中其他两个选择的动态变化来填充一个选择。我从教程网站复制了大部分内容。非常希望我的选择被填充两次,如下所示:
为什么要渲染两次?经过一番思考,看来onLoad
被解雇了多次。我有一种新情况,我的数据库查询返回一行,但这会使选择选项循环4次。
这是我的控制人:
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "category", "budget", "vendor", "related" ]
update_related() {
let dropdown = this.relatedTarget;
dropdown.length = 0;
let defaultOption = document.createElement('option');
defaultOption.text = 'Select parent expenditure...';
dropdown.add(defaultOption);
dropdown.selectedIndex = 0;
const url = '/related_expenditures.json?vendor_id=' + this.vendorTarget.value + '&budget_id=' + this.budgetTarget.value;
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.value = data[i].id;
option.text = data[i].related_select_label;
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();
}
}