嗨,我在做依赖下拉列表。

如果<select>不在表td中,则该代码有效。

但是,如果select标签在表td中,则ajax将无法返回到表td中的元素。我该如何解决?

    <table>
     <tr>
      <td>
        <label>Country:</label><br/>
        <select name="country" id="country-list" onChange="getState(this.value);">
        <option value="">Select Country</option>
        <?php
        foreach($results as $country) {
        ?>
        <option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option>
        <?php
        }
        ?>
        </select>
      </td>
    </tr>
    <tr>
       <td>
        <label>State:</label><br/>
        <select name="state" id="state-list" class="demoInputBox">
        <option value="">Select State</option>
        </select>
       </td>
    </tr>
 </table>


<script>
function getState(val) {
    $.ajax({
    type: "POST",
    url: "get_state.php",
    data:'country_id='+val,
    success: function(data){
        $("#state-list").html(data);
    }
    });
}
</script>


在get_state.php页面中

<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["country_id"])) {
    $query ="SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
    $results = $db_handle->runQuery($query);
?>
    <option value="">Select State</option>
<?php
    foreach($results as $state) {
?>
    <option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option>
<?php
    }
}
?>

最佳答案

您的代码似乎正常工作。如果不了解您的数据,就不可能说出什么问题。复制此代码段,然后尝试通过输入实际状态数据来重现您的问题。



/// fake jQuery.ajax
function $ajax(params) {
  params.success('<option value="1">S1</option><option value="2">S2</option><option value="3">S3</option><option value="4">S4</option>');
}

function getState(val) {
    $ajax({
    type: "POST",
    url: "get_state.php",
    data:'country_id='+val,
    success: function(data){
        $("#state-list").html(data);
    }
    });
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
     <tr>
      <td>
        <label>Country:</label><br/>
        <select name="country" id="country-list" onChange="getState(this.value);">
        <option value="">Select Country</option>
        <option value="1">Country 1</option>
        </select>
      </td>
    </tr>
    <tr>
       <td>
        <label>State:</label><br/>
        <select name="state" id="state-list" class="demoInputBox">
        <option value="">Select State</option>
        </select>
       </td>
    </tr>
 </table>

关于javascript - 为什么ajax无法将数据返回到表td中的元素?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42187080/

10-09 21:14