</select>
<br><br>
<input type="button" value="Valider" onclick="getData()">
</form>
<script>
function getData() {
$.ajax({
url: "fic.json",
type: "GET",
dataType: 'json',
success: function(data)
{
localStorage.setItem("data",JSON.stringify(data))
}
})
list =JSON.parse(localStorage.getItem("data"))
l = "";
i = 0;
list.voiture.forEach(function(el) {
l += `<option value="${i}">${el.marque}</option>`;
i++;
});
document.getElementById("voiture").innerHTML = l;
}
</script>
Assistant
To improve your code and ensure it functions correctly, there are a few adjustments that you can make. You need to ensure that the asynchronous nature of the AJAX call does not lead to issues with accessing the data before it is fully fetched and stored in localStorage.
Here is an improved version of your code:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- Inclusion de jQuery -->
</head>
<body>
<h2>Sélectionnez une voiture :</h2>
<form>
<label for="voiture">Voiture :</label>
<select id="voiture" name="voiture"></select>
<br><br>
<input type="button" value="Valider" onclick="getData()">
</form>
<script>
function getData() {
$.ajax({
url: "fic.json",
type: "GET",
dataType: 'json',
success: function(data) {
localStorage.setItem("data", JSON.stringify(data));
populateCarOptions();
},
error: function() {
console.error("An error occurred while fetching the data.");
}
});
}
function populateCarOptions() {
const dataString = localStorage.getItem("data");
if (dataString) {
const list = JSON.parse(dataString);
let options = "";
list.voiture.forEach((el, i) => {
options += `<option value="${i}">${el.marque}</option>`;
});
document.getElementById("voiture").innerHTML = options;
} else {
console.error("No data found in localStorage.");
}
}
</script>
</body>
</html>
Explanation of Changes:
Success Callback Enhancement: The success callback now directly calls the populateCarOptions function after storing the data in localStorage. This ensures that the option elements are populated only if the AJAX call is successful.
Error Handling: The error callback is added to handle any issues that might occur during the AJAX request.
Separate Function for Populating Options: A separate function, populateCarOptions, is created to handle the population of the <select> element. This makes the code cleaner and easier to understand and maintain.
Use Conditional Logic to Ensure Data Presence: The presence of data in localStorage is checked before attempting to parse and use it to populate the <select> options. This prevents potential errors if the data is not yet available or if the AJAX call fails.
These changes should ensure smoother execution and make the code more robust.