页面加载时通过jQuery/Ajax/PHP从数组自动填充多个下拉选择框(避免代码重复)
Got it, let's get all three dropdowns populated cleanly without duplicating code. Here's a streamlined approach that uses a single AJAX request and a reusable function for dropdown population:
Step 1: Update Your PHP Logic (logic.php)
First, we'll modify the PHP to return all three datasets in one JSON response instead of just the CPU data. We also need to decode the JSON files into actual arrays so we can package them properly:
<?php // Read and decode each JSON file into associative arrays $cpuArr = json_decode(file_get_contents('data/cpu.json'), true); $motherboardsArr = json_decode(file_get_contents('data/motherboard.json'), true); $videocardArr = json_decode(file_get_contents('data/video-card.json'), true); // Handle the AJAX request if(isset($_POST['request']) && $_POST['request'] === 1){ // Package all three datasets into a single associative array $response = [ 'cpus' => $cpuArr, 'motherboards' => $motherboardsArr, 'videocards' => $videocardArr ]; // Send the JSON response echo json_encode($response); exit; // Prevent any extra output after the response } ?>
Step 2: Refactor the jQuery Code
We'll create a reusable function to populate any dropdown, then use a single AJAX call to fetch all data and populate each dropdown with the generic function:
$(document).ready(function(){ // Generic function to populate a dropdown with data function populateDropdown(selectId, data, defaultOptionText) { const $selectElement = $('#' + selectId); // Reset the dropdown with the default option $selectElement.html(`<option value="0">${defaultOptionText}</option>`); // Loop through the data and add each option data.forEach(item => { $selectElement.append(`<option value="${item.ID}">${item.Name}</option>`); }); } // Single AJAX request to fetch all dropdown data $.ajax({ url: 'logic.php', type: 'post', data: {request: 1}, dataType: 'json', success: function(fullResponse){ // Populate each dropdown using our reusable function populateDropdown('cpu', fullResponse.cpus, '-Select CPU-'); populateDropdown('motherboard', fullResponse.motherboards, '-Select motherboard-'); populateDropdown('video-card', fullResponse.videocards, '-Select Video Card-'); }, error: function(xhr, status, error){ // Optional: Log errors for debugging console.error('Failed to load dropdown data:', error); } }); });
Step 3: Keep Your HTML As-Is
Your existing HTML doesn't need any changes—we're using the same id attributes you already defined for each dropdown:
<select id='cpu'> <option value="0">-Select CPU-</option> </select> <select id='motherboard'> <option value="">-Select motherboard-</option> </select> <select id='video-card'> <option value="">-Select Video Card-</option> </select>
Key Benefits of This Approach:
- Single AJAX Request: Reduces server round-trips compared to three separate requests, which is more efficient.
- No Code Duplication: The
populateDropdownfunction handles all the repetitive DOM work—you just call it with different parameters for each dropdown. - Scalable: If you need to add more dropdowns later, you just add another entry in the PHP response and one more
populateDropdowncall.
内容的提问来源于stack exchange,提问作者Boysa

