我已经创建了一个表单,并且正在尝试将从 API 获取的数据添加到选项字段。
以下是我的网站链接。我在下面放置了两个不同的示例。您可以向下滚动页面并能够看到我的意思。
我使用了这个示例代码,但它不起作用。
new TomSelect("#makeField", {
sortField: {
field: "text",
direction: "desc",
},
});
php代码
<?php
/**
* Template Name: Custom Page Template
*
* This is the template file for generic pages.
* You can customize this file to fit your specific needs.
*
* @package Pyro
*/
get_header(); ?>
<?php get_template_part("template-parts/navigation"); ?>
<section class="pageDefault">
<form id="form__lead">
<label for="yearField">Select Year:</label>
<select id="yearField" name="yearField" class="vehicleYear">
<option value="">Select year</option>
<option value="2024">2024</option>
<option value="2023">2023</option>
<option value="2022">2022</option>
<option value="2021">2021</option>
<option value="1958">1958</option>
</select><br/>
<label for="makeField">Select Make:</label>
<select id="makeField" name="makeField" class="vehicleMake">
<!-- Options go here -->
<option value="">Select make</option>
</select>
</form>
</section>
<?php get_footer(); ?>
JavaScript 代码
import axios from "axios";
import TomSelect from "tom-select";
const yearField = document.getElementById("yearField");
const makeField = document.getElementById("makeField");
const modelField = document.getElementById("modelField");
let selectedYear = "";
new TomSelect("#yearField", {
sortField: {
field: "text",
direction: "desc",
},
});
// Event listener to update selectedYear when the year select field changes
yearField.addEventListener("change", function () {
selectedYear = yearField.value;
fetchData(); // Fetch data when the year is changed
});
function fetchData() {
const apiEndpoint = `https://done.ship.cars/makes/?year=${selectedYear}`;
axios
.get(apiEndpoint)
.then(function (response) {
const data = response.data; // Assuming the response is an array of options
populateDropdown(data, makeField);
console.log(data);
})
.catch(function (error) {
console.error("Error fetching data:", error);
console.log("Response status:", error.response.status);
console.log("Response data:", error.response.data);
});
}
function populateDropdown(data, dropdown) {
dropdown.innerHTML = "";
const defaultOption = document.createElement("option");
defaultOption.value = "";
defaultOption.textContent = "Select make";
dropdown.appendChild(defaultOption);
data.forEach(function (item) {
const option = document.createElement("option");
option.value = item.make;
option.textContent = item.make;
dropdown.appendChild(option);
});
}
我正在尝试将获取的数据加载到 Tom select js 库生成的选项字段中。我能够获取数据,但无法将其动态分配给选项字段。
初始化 TomSelect 时获取句柄:
var make_select = new TomSelect("#makeField", {
sortField: {
field: "text",
direction: "desc",
},
});
然后在您的 AJAX 调用成功执行后(例如在您的 populateDropdown 函数中)首先清除所有先前设置的数据:
make_select.clearOptions();
然后在 forEach 中使用以下方法在另一个选项之后添加一个选项:
make_select.addOption({
id: 4,
title: 'Something New',
url: 'http://google.com'
});