通过另一个选择填充下拉列表

时间:2018-06-07 06:28:08

标签: javascript php ajax

我创造了这个:

User: <select id="sel_depart">
    <option value="0">All users</option>    
<?php
$all_users = User::getUsersAdmin();
foreach($all_users as $value){ ?>
        <option value="<?php echo $value->id; ?>" <?php if($user_id == $value->id) echo "selected" ?>><?php echo $value->username; ?></option>
<?php } ?> 
</select>

Locker: <select id="sel_user">
    <option value="0">All lockers</option>  
</select>

我有这个javascript:

$(document).ready(function(){

    $("#sel_depart").change(function(){
        var user_id = $(this).val();

        $.ajax({
            url: 'admin/get_lockers.php',
            type: 'post',
            data: {user_id:user_id},
            dataType: 'json',
            success:function(response){

                var len = response.length;

                $("#sel_user").empty();
                for( var i = 0; i<len; i++){
                    var id = response[i]['id'];
                    var name = response[i]['name'];

                    $("#sel_user").append("<option value='"+id+"'>"+name+"</option>");

                }
            }
        });
    });

});

get_lockers.php输出为:

[{"id":2,"name":"edees"},{"id":3,"name":"20171114_154920"}]

有什么问题?当我从下拉列表中选择用户时,不会使用选项填充锁定器下拉列表。

1 个答案:

答案 0 :(得分:0)

请试试这个,它应该有效!

    $(document).ready(function(){

$("#sel_depart").change(function(){
    var user_id = 2;
        $.ajax({
        url: 'admin/get_lockers.php',
        type: 'GET',
        data: {user_id:user_id},
        dataType: 'json',
        success:function(response){
        //Add this line and try
		response =  JSON.parse(JSON.stringify(response));
          var len = response.length;
            $('#sel_user').find('option').remove().end();
            for( var i = 0; i<len; i++){
                var id = response[i]['id'];
                var name = response[i]['name'];
                var option = new Option(name, id);
               $('#sel_user').find('option').end().append($(option));

			}
			}
    });
});

});
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>


<p>Select Department</p>
<select id="sel_depart" name="this" class="input-sm input-s form-control">
    <option>Test A</option>
    <option>Test B</option>
    <option>Test C</option>
    <option>Test D</option>
</select>

<p>Select User</p>

<select id="sel_user" name="this" class="input-sm input-s form-control">
    <option>Test A</option>
    <option>Test B</option>
    <option>Test C</option>
    <option>Test D</option>
</select>

</body>
</html>