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

AJAX调用未传参无报错及根据选中州获取城市列表问题咨询

Let's Tackle Your Two Technical Questions

Question 1: How to Fetch City List Based on Selected State

Your current setup is almost there, but there are a couple of key fixes needed to get it working properly:

1. Fix the Server-Side PHP Code

In your get_city() function, you have print_r($query); exit(); which stops execution before generating the city option HTML. Remove those lines so the dropdown options can be rendered. Also, add a check to ensure the id parameter is received correctly:

public function get_city() {
    // Check if state ID is provided
    if (!isset($_POST['id']) || empty($_POST['id'])) {
        echo '<option value="" disabled selected>Please select a state first</option>';
        exit();
    }

    $id = $_POST['id'];
    $query = $this->common->select_data_by_id('city', 'state', $id, '*', '');
    
    // Start building the city options
    echo '<option value="" disabled selected>Choose your city</option>';
    if (!empty($query)) {
        foreach($query as $place) {
            echo '<option value="'.$place['city_name'].'">'.$place['city_name'].'</option>';
        }
    } else {
        echo '<option value="" disabled>No cities found for this state</option>';
    }
    exit();
}

2. Update the AJAX Success Handler

Uncomment the line that populates the city dropdown, and remove the debug alert (or keep it temporarily for testing):

$(document).ready(function() {
    jQuery('#state').change(function() {
        var id = jQuery(this).val();
        if (!id) return; // Exit if no state is selected
        
        jQuery.ajax({
            type: 'post',
            url: "<?php echo base_url().'routes/get_city' ?>",
            data: { id: id }, // Use object syntax for cleaner data passing
            success: function(result) {
                jQuery('.city').html(result); // Populate the city dropdown
            },
            error: function(xhr, status, error) {
                console.error("AJAX Error:", status, error); // Add error logging
            }
        });
    });
});

Question 2: Troubleshooting AJAX Call Not Passing Data (No Errors Thrown)

If your AJAX call isn't sending data and isn't throwing errors, follow these steps to diagnose the issue:

  • Check the Browser Network Tab:
    Open your browser's developer tools (F12), go to the Network tab, and trigger the state change. Look for the AJAX request to get_city:

    • Confirm the request method is POST
    • Verify the request URL is correct (no typos in the base URL or route)
    • Check the "Form Data" section to see if the id parameter is being sent
  • Validate Server-Side Receipt:
    Add debug code to your get_city() function to confirm if the data is reaching the server:

    public function get_city() {
        var_dump($_POST); // Check if id is present
        exit();
    }
    

    If $_POST is empty, you might need to check if your server requires CSRF tokens (common in frameworks like CodeIgniter) or if the request content type is set correctly.

  • Add AJAX Error Handling:
    Your current code only has a success handler. Add error callbacks to catch silent failures:

    jQuery.ajax({
        // ... existing options
        error: function(xhr, status, error) {
            console.log("Request failed:", xhr.responseText);
            alert("Failed to load cities: " + error);
        },
        complete: function(xhr) {
            console.log("Request status:", xhr.status);
        }
    });
    
  • Check for Syntax or Scope Issues:

    • Ensure there are no typos in your JavaScript (e.g., misspelled id variable, incorrect selector for the state dropdown)
    • Confirm that base_url() is generating a valid absolute URL (echo it out in the HTML to verify)
    • If using CodeIgniter, make sure the routes/get_city route is properly defined in your routes file
  • Verify State Dropdown Value:
    Ensure the selected state option has a non-empty state_id value. You can test this by adding console.log(id) right after var id = jQuery(this).val();


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:09:11