Using Ajax To Populate A Select Box

后端 未结 3 554
悲&欢浪女
悲&欢浪女 2020-12-19 03:17

Ok, this is my very first attempt at Ajax and its driving me insane as I really cant get my head round it. What im trying to do is populate the first box with the customers

3条回答
  •  Happy的楠姐
    2020-12-19 03:56

    Looks as if you are creating an array of JSON objects on each itteration in select.php.

    Below the array is generated in PHP and then JSON encoded, which in my option is the best way to generate JSON strings.

    // select.php
    
    $id = $_GET['customerId'];
    $sql = 'SELECT * FROM vehicles WHERE customerID = ' . $id;
    $result = $db->query($sql);
    
    $json = array();
    while ($row = $result->fetch_assoc()) {
      $json[] = array(
        'id' => $row['vehicleId'],
        'name' => $row['vehicleId'] // Don't you want the name?
      );
    }
    echo json_encode($json);
    
    // Test.php
    
    $('#customer').on('change', function (){
      $.getJSON('select.php', {customerId: $(this).val()}, function(data){
    
        var options = '';
        for (var x = 0; x < data.length; x++) {
          options += '';
        }
        $('#vehicle').html(options);
      });
    });
    

提交回复
热议问题