Ajax选择选项组不起作用

时间:2016-05-31 07:10:12

标签: php jquery ajax

类别和服务存储在两个表(类别,服务)中。我需要根据人员选择将所有类别和服务加载到一个选择框中。

//Jquery
$('.staff').change(function() {
    var services = $('.service').empty();
    $('<option value="" disabled selected hidden>--Select Service--</option>').appendTo(services);
    $.get('ajax_service.php', {tutor: $(this).val()}, function(result) {
        $.each(JSON.parse(result), function(index, item) {
            $('<optgroup label="' + index + '">').appendTo(services);
                $.each(item, function (name, value) {
                    $('<option value="' + name + '">' + value + '</option>').appendTo(services);
                });
            $('</optgroup>').appendTo(services);
        });
    });
});

//ajax_service.php
if(isset($_GET['staff'])) {
    $staff_id = $_GET['staff'];
    $sql = "SELECT c.category_id, c.category_name, s.service_id, s.service_name "
        . "FROM service s "
        . "INNER JOIN category c ON s.category_id = c.category_id "
        . "WHERE s.staff_id = ? "
        . "ORDER BY s.sort_order ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array($staff_id));
    $services = $stmt->fetchAll();
    $groups = array();
    foreach ($services as $service) {
        $groups[$service['category_name']][$service['service_id']] = $service['service_name'];
    }
    echo json_encode($groups);
}

此代码加载所有类别和服务,但选项组不能按预期工作 Result

结果HTML代码

<select class="service" name="ddlService" id="ddlService">
    <option value="" disabled="" selected="" hidden="">--Select Service--</option>
    <optgroup label="Advertising"></optgroup>
    <option value="1">Adware</option>
    <option value="2">Brands</option>
    <option value="3">Modeling</option>
    <option value="4">Sponsorships</option>
    <option value="5">Press Release</option>
</select>

这段代码有什么问题?谁能帮我跟踪这个问题?非常感谢你的时间。

1 个答案:

答案 0 :(得分:1)

//Jquery
$('.staff').change(function() {
    var services = $('.service');
    var html='';
    $('<option value="" disabled selected hidden>--Select Service--</option>').appendTo(services);
    $.get('ajax_service.php', {tutor: $(this).val()}, function(result) {

        $.each(JSON.parse(result), function(index, item) {
          html+='<optgroup label="' + index + '">';

                $.each(item, function (name, value) {
                   html+= '<option value="' + name + '">' + value +'</option>');
                });
            html+= '</optgroup>');
        });
    });
services.append(html);
});