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

Ajax联动下拉列表失效求助(附完整代码与表结构)

Hey there, let's walk through fixing your broken Ajax cascading dropdowns. I spotted several key issues in your code that are causing the problem—let's tackle them one by one:

1. Your getstate.php and getdis.php return full HTML pages (not just options)

Right now, these scripts send back a complete HTML document with <html>, <body>, and <form> tags. When you inject this into your <select> element, it's invalid markup and breaks the dropdown. You only need to output the <option> elements directly.

Fix for getstate.php:

<?php
// Remove all unnecessary HTML tags
$con = mysqli_connect("localhost", "root", "", "doctor_db"); // Switch to modern mysqli extension
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

// Sanitize input to prevent SQL injection
$q = mysqli_real_escape_string($con, $_GET["q"]);
$sql = "select * from specialty_tb where lid='".$q."'";
$res = mysqli_query($con, $sql);

echo "<option value='0'>-----select specialist-----</option>";
while($ar = mysqli_fetch_array($res)){
    echo "<option value='".$ar[0]."'>".$ar[1]."</option>";
}

mysqli_close($con);
?>

Same fix applies to getdis.php:

<?php
$con = mysqli_connect("localhost", "root", "", "doctor_db");
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

$q = mysqli_real_escape_string($con, $_GET["q"]);
$sql = "select * from doctor_details where sid='".$q."'";
$res = mysqli_query($con, $sql);

echo "<option value='0'>-----select doctor-----</option>";
while($ar = mysqli_fetch_array($res)){
    echo "<option value='".$ar[0]."'>".$ar[1]."</option>";
}

mysqli_close($con);
?>

2. You're using deprecated mysql_* functions

The mysql_* extension was removed in PHP 7+, so your database connections might be failing silently (you have error_reporting(0) turned on, which hides errors!). Switch to mysqli_* functions as shown above—they're backward-compatible, secure, and supported.

3. Global xmlHttp variable causes request conflicts

Your two Ajax functions (showHint and showHide) both use a global xmlHttp variable. If the user triggers a second request before the first finishes, it overwrites the variable and breaks the first request. Declare xmlHttp as a local variable inside each function:

Fixed JavaScript in index.php:

<script type="text/javascript">
function showHint(str){
    if(str.length==0){
        document.getElementById("ddlstate").innerHTML="";
        return;
    }
    let xmlHttp; // Local variable to avoid conflicts
    if(window.XMLHttpRequest){
        xmlHttp=new XMLHttpRequest();
    } else {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlHttp.onreadystatechange=function(){
        if(xmlHttp.readyState==4 && xmlHttp.status==200){
            document.getElementById("ddlstate").innerHTML=xmlHttp.responseText;
        }
    }
    // Encode URI to handle special characters in input
    xmlHttp.open("GET","getstate.php?q="+encodeURIComponent(str),true);
    xmlHttp.send();
}

function showHide(str){
    if(str.length==0){
        document.getElementById("ddldis").innerHTML="";
        return;
    }
    let xmlHttp; // Local variable
    if(window.XMLHttpRequest){
        xmlHttp=new XMLHttpRequest();
    } else {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlHttp.onreadystatechange=function(){
        if(xmlHttp.readyState==4 && xmlHttp.status==200){
            document.getElementById("ddldis").innerHTML=xmlHttp.responseText;
        }
    }
    xmlHttp.open("GET","getdis.php?q="+encodeURIComponent(str),true);
    xmlHttp.send();
}
</script>

4. Fix incomplete HTML in index.php

Your form and button tags aren't closed properly, which can mess up the DOM structure. Add the missing closing tags:

<!-- Close the button and remaining div/form tags in index.php -->
<button class="search" name="search" id="search" type="submit"><i class="flaticon-magnifier-tool"></i></button>
</div> <!-- Close col-lg-2 div -->
</div> <!-- Close col-lg-4 form-group div -->
</form> <!-- Close main form -->

5. Enable error reporting for debugging

Temporarily remove error_reporting(0); from index.php so you can see any PHP errors that might be happening. This will help you catch issues like database connection failures or SQL syntax errors.

Bonus: Add a loading state (optional)

To improve user experience, you can add a loading message while the Ajax request is in progress. For example, in showHint:

xmlHttp.onreadystatechange=function(){
    if(xmlHttp.readyState==1){
        document.getElementById("ddlstate").innerHTML="<option>Loading...</option>";
    } else if(xmlHttp.readyState==4 && xmlHttp.status==200){
        document.getElementById("ddlstate").innerHTML=xmlHttp.responseText;
    }
}

After applying these fixes, your cascading dropdowns should work as expected. Start with fixing the response content from the PHP scripts—this is the most critical issue causing the dropdowns to fail.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:44:34