You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

页面加载时通过jQuery/Ajax/PHP从数组自动填充多个下拉选择框(避免代码重复)

Solution to Populate Multiple Dropdowns Without Repeating Code

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 populateDropdown function 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 populateDropdown call.

内容的提问来源于stack exchange,提问作者Boysa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:49:10