2016-05-31 108 views
0

類別和服務存儲在兩個表(類別,服務)中。我需要根據員工選擇將所有類別和服務加載到單個選擇框中。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
//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); 
});