Heim > Fragen und Antworten > Hauptteil
Ich habe eine Website geschrieben, auf der Benutzer WLAN-Passwörter ändern können.
Daten werden in data/data.json
gespeichert. Dazu gehören die Zimmernummer, der AP-Name und das Passwort.
[ {"Room": "room 1", "AP name": "ap 1", "password": "12345678"}, {"Room": "room 2", "AP name": "ap 2", "password": "12345678"} ]
Es gibt ein Dropdown-Menü, in dem Benutzer ihren Raum auswählen können. Dropdown-Optionen werden von JavaScript generiert, indem Daten aus einer JSON-Datei abgerufen werden. Aber jetzt werden in der Dropdown-Liste keine Optionen angezeigt.
<tr> <td>Select your room:</td> <td> <select id="room" name="room" required> <option value="" selected>Select room</option> <!-- Room options will be populated by JavaScript --> </select> </td> </tr>
document.addEventListener('DOMContentLoaded', loadRoomNumbers); // Function to load room numbers from data.json function loadRoomNumbers() { const roomSelect = document.getElementById('room'); fetch('data/data.json') .then(response => { if (!response.ok) { throw new Error('Could not load data.json'); } return response.json(); }) .then(roomsData => { roomsData.forEach(roomData => { const option = document.createElement('option'); option.value = roomData.Room; option.textContent = roomData.Room; roomSelect.appendChild(option); }); }) .catch(error => { console.error('Error fetching room data:', error); }); }
Darf ich wissen, welches Teil falsch ist und wie ich es beheben kann? Danke
P粉2860467152024-04-01 11:55:30
坦白说,你的代码相当混乱。
例如:您为 DOMContentLoaded
注册了两次事件监听器(在代码的顶部和底部),它们都执行 loadRoomNumbers
。
让我正确重写您的 loadRoomNumbers
方法:
document.addEventListener('DOMContentLoaded', loadRoomNumbers); // Function to load room numbers from data.json async function loadRoomNumbers() { const roomSelect = document.getElementById('room'); try { const response = await fetch('data/data.json') if (!response.ok) { throw `Response not ok (${response.status})` } const rooms = await response.json() rooms.forEach(roomData => { const option = document.createElement('option'); option.value = roomData.Room; option.textContent = roomData.Room; roomSelect.appendChild(option); }); } catch (error) { console.error('Error fetching room data:', error); } }
或者在一个工作示例中:
document.addEventListener('DOMContentLoaded', loadRoomNumbers); // Function to load room numbers from data.json async function loadRoomNumbers() { const roomSelect = document.getElementById('room'); try { // This has to be replaced by fetch('data/data.json') of course const rooms = await [ {"Room": "room 1","AP name": "ap 1","password": "12345678"}, {"Room": "room 2","AP name": "ap 2","password": "12345678"} ] rooms.forEach(roomData => { const option = document.createElement('option'); option.value = roomData.Room; option.textContent = roomData.Room; roomSelect.appendChild(option); }); } catch (error) { console.error('Error fetching room data:', error); } }
Select your room: