AJAX在页面加载之前运行onchange事件

Mei*_*uri 7 javascript php mysql ajax

所以这是场景.我有2次下降.第一个具有onchange在第二个下拉列表中加载数据的功能.它完全正常工作,但我想使用该onchange功能实现在第二个下拉列表中加载数据onload.

这是我的功能:

function fetch_select(val)
    {
       $.ajax({
         type: 'post',
         url: '../function/fetch_car_package.php',
         data: {
           get_option:val
         },
         success: function (response) {
           document.getElementById("new_select").innerHTML=response; 
         }
       });
    }
Run Code Online (Sandbox Code Playgroud)

这是我的下拉菜单:

<select name='cItemID' onchange="fetch_select(this.value);">
    <?php
    $sql = "";
    $sth = $dbh->prepare($sql);
    $sth->execute();
    $result = $sth->fetchAll();

    foreach($result as $row) {
        if ($_SESSION['cItemID'] == $row['Item ID']) {
            $selected = "selected";
        } else {
            $selected = '';
        }
        echo "<option value='".$row['Item ID']."' $selected>".$row['Item Name']."</option>";
    }
    ?>
</select>
Run Code Online (Sandbox Code Playgroud)

我的ajax处理页面:

if(isset($_POST['get_option'])){
    $ItemID = $_POST['get_option'];
    $sql = "";
    $sth = $dbh->prepare($sql);
    $sth->execute();
    $result = $sth->fetchAll();

    foreach($result as $row) {
        echo "<option value='".$row['cCLID']."'    $selected>".$row['cDescription']."</option>";
    }

    exit;
}
Run Code Online (Sandbox Code Playgroud)

小智 1

尝试添加一个计数器变量来跟踪迭代<option>中的第二个foreach

<select name='cItemID' > 
    <?php 
    $sql = $store =""; 
    $sth = $dbh->prepare($sql);
    $sth->execute(); 
    $count=0;
    $result = $sth->fetchAll();

    foreach($result as $row) {
        $count++;
         if ($_SESSION['cItemID'] == $row['Item ID']) {
            $selected = "selected";
        } 
        else {
            $selected = '';
        }

        $store = ($count==2)? "fetch_select(this.value)" : " ";
        echo "<option onselect='".$store."' value='".$row['Item ID']."' $selected>".$row['Item Name']."</option>";
    } 
    ?> 
</select>
Run Code Online (Sandbox Code Playgroud)

如果值达到 2,它将添加一个$store包含所需 javascript 的字符串,否则离开,如果您选择第二个选项,它将触发具有所选值的函数。$countonselect=" "

您可以使用onfocusonclick或标签上的任何其他 javascript 事件<option>来完成您的工作。