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

如何将AJAX调用从外部PHP文件改为当前页面(二级下拉联动)

How to Integrate AJAX City Fetching into the Same Page

Great news that your current setup is working! Let's adjust your code so you don't need a separate get-City.php file—we'll handle everything right in index.php. Here's how to do it step by step:

Step 1: Add AJAX Request Handling to index.php

At the top of your index.php file, right after including the database connection, we'll add code to detect and respond to the AJAX request for city data. This code will only run when the request is asking for cities; otherwise, it'll load the regular page.

<?php
include('connection.php');

// Check if this is an AJAX request to get cities
if (isset($_GET['action']) && $_GET['action'] === 'get_cities' && isset($_GET['region_id'])) {
    // Sanitize input to prevent SQL injection
    $region_id = intval($_GET['region_id']);
    
    // Query to fetch cities for the selected region (adjust table/column names to match your DB)
    $query = "SELECT id, city_name FROM cities WHERE region_id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $region_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    // Build array of city data
    $cities = [];
    while ($row = $result->fetch_assoc()) {
        $cities[] = [
            'id' => $row['id'],
            'name' => $row['city_name']
        ];
    }
    
    // Send data as JSON
    header('Content-Type: application/json');
    echo json_encode($cities);
    
    // Exit to avoid loading the rest of the page in the AJAX response
    exit;
}
?>

Step 2: Update Your JavaScript AJAX Call

Modify your JavaScript to send the request to index.php instead of get-City.php, and include the action parameter so our PHP code knows to handle it as an AJAX request. Here are two common variants:

Vanilla JavaScript Version

<script>
// Assuming your first dropdown has ID "regionDropdown"
document.getElementById('regionDropdown').addEventListener('change', function() {
    const regionId = this.value;
    const cityDropdown = document.getElementById('cityDropdown');
    
    // Clear existing city options
    cityDropdown.innerHTML = '<option value="">Select a city...</option>';
    
    if (regionId) {
        // Send request to index.php with action and region_id parameters
        fetch(`index.php?action=get_cities&region_id=${regionId}`)
            .then(response => response.json())
            .then(data => {
                // Add each city to the dropdown
                data.forEach(city => {
                    const option = document.createElement('option');
                    option.value = city.id;
                    option.textContent = city.name;
                    cityDropdown.appendChild(option);
                });
            })
            .catch(error => console.error('Error loading cities:', error));
    }
});
</script>

jQuery Version (if you were using it originally)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$('#regionDropdown').change(function() {
    const regionId = $(this).val();
    $('#cityDropdown').html('<option value="">Select a city...</option>');
    
    if (regionId) {
        $.ajax({
            url: 'index.php',
            type: 'GET',
            data: {
                action: 'get_cities',
                region_id: regionId
            },
            dataType: 'json',
            success: function(data) {
                $.each(data, function(index, city) {
                    $('#cityDropdown').append(`<option value="${city.id}">${city.name}</option>`);
                });
            },
            error: function(xhr, status, error) {
                console.error('Error loading cities:', error);
            }
        });
    }
});
</script>

Key Notes:

  • SQL Injection Protection: We used intval() and prepared statements to ensure input safety—never skip this step to protect your database!
  • JSON Content Header: Setting header('Content-Type: application/json') tells the browser to parse the response as JSON correctly.
  • Exit After AJAX Response: The exit; command stops the rest of the page from being included in the AJAX response, which would break the JSON data.

That's it! Now your AJAX request will hit the same index.php page, and the PHP code will handle either loading the regular page or returning city data based on the request parameters.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:44:26