javascript
// script.js// 汽车品牌
const makes = ["所有品牌", "奥迪", "宝马", "奔驰", "凯迪拉克", "雪佛兰", "道奇", "福特", "本田", "现代"];// 汽车型号
const models = {"奥迪": ["A3", "A4", "A5", "A6", "A7", "A8", "Q3", "Q5", "Q7", "Q8"],"宝马": ["1系", "3系", "5系", "7系", "X1", "X3", "X5", "X6", "X7"],"奔驰": ["A级", "C级", "E级", "S级","GLA", "GLC", "GLE", "GLS"],"凯迪拉克": ["ATS", "CTS", "CT6", "ESCALADE", "XT4", "XT5", "XT6"],"雪佛兰": ["科迈罗", "科鲁兹", "索纳塔", "探界者", "创酷", "探险者"],"道奇": ["挑战者", "酷威", "蝰蛇", "公羊"],"福特": ["F-150", "福克斯", "蒙迪欧", "野马"],"本田": ["思域", "雅阁", "CR-V", "奥德赛", "飞度"],"现代": ["伊兰特", "索纳塔", "途胜", "圣达菲", "伊兰特"],
};// 汽车年份
const years = [];
for (let i = 2010; i <= new Date().getFullYear(); i++) {years.push(i);
}// 初始化表单
const form = document.getElementById("form");
const makeSelect = document.getElementById("make");
const modelSelect = document.getElementById("model");
const yearSelect = document.getElementById("year");
const locationInput = document.getElementById("location");
const resultsDiv = document.getElementById("results");// 创建品牌下拉框
for (let i = 0; i < makes.length; i++) {const option = document.createElement("option");option.value = makes[i];option.textContent = makes[i];makeSelect.appendChild(option);
}// 创建型号下拉框
const populateModels = (make) => {modelSelect.innerHTML = "";const option = document.createElement("option");option.value = "";option.textContent = "所有型号";modelSelect.appendChild(option);if (make in models) {for (let i = 0; i < models[make].length; i++) {const option = document.createElement("option");option.value = models[make][i];option.textContent = models[make][i];modelSelect.appendChild(option);}}
};// 创建年份下拉框
for (let i = 0; i < years.length; i++) {const option = document.createElement("option");option.value = years[i];option.textContent = years[i];yearSelect.appendChild(option);
}// 表单提交事件
form.addEventListener("submit", (e) => {e.preventDefault();// 获取表单数据const make = makeSelect.value;const model = modelSelect.value;const year = yearSelect.value;const location = locationInput.value;// 使用 fetch API 查询数据fetch("api/garages", {method: "POST",headers: {"Content-Type": "application/json",},body: JSON.stringify({make,model,year,location,}),}).then((res) => res.json()).then((data) => {// 显示结果resultsDiv.innerHTML = `
最近的修理厂:
`;if (data.length === 0) {resultsDiv.innerHTML += `
没有找到符合条件的修理厂。
`;return;}for (let i = 0; i < data.length; i++) {const garage = data[i];resultsDiv.innerHTML += `
${garage.name}:${garage.address},电话:${garage.phone}
`;}}).catch((error)=> {console.error("Error querying API:", error);alert("查询失败。请重试。");});
});// 品牌选择事件
makeSelect.addEventListener("change", (e) => {populateModels(e.target.value);
});