使用Ajax填充选择框

时间:2013-06-28 14:40:03

标签: javascript php jquery ajax

好吧,这是我第一次尝试阿贾克斯,它让我疯狂,因为我真的无法理解它。我想要做的是从数据库填充客户的第一个框,然后使用customerID从select.php脚本中选择数据库中的所有vehicleID。 正在发生的事情是客户框被选中,但当选择客户时没有任何事情发生。

这是我的Test.php文件:

<?php include 'connectmysqli.php'; ?>
<html>

    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <title>Select test</title>
        <script src="./js/jquery/jquery.js"></script>
        <script type="text/javascript" charset="utf-8">
            $$('#customer')
                .on('change', function () {
                    $.getJSON('select.php', { customerId: $(this)
                            .val() }, function (data) {

                        var options = '';
                        for (var x = 0; x < data.length; x++) {
                            options += '<option value="' + data[x][
                                    'id'] + '">' + data[x]['reg'] +
                                '</option>';
                        }
                        $('#vehicle')
                            .html(options);
                    });
                });

        </script>
    </head>

    <body>
        <select id="customer">
                <?php
        $sql = <<<SQL
        SELECT *
        FROM `customers`
        SQL;
        if(!$result = $db->query($sql)){ die('There was an error running the query [' . $db->error . ']');}
        while($row = $result->fetch_assoc()){
        if ($row['bussinessname'] == ''){$name = $row['title'].' '.$name = $row['firstname'].' '.$name = $row['surname'];}else
        {$name = $row['bussinessname'];}
        echo '<option value="'.$row['customerID'].'">'.$name.'</option>';
        }
        echo '</select></p>'; ?>
        </select>
        <select id="vehicle">
                </select>
    </body>

</html>

这是我的select.php文件:

<?php include 'connectmysqli.php'; ?>
<?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'],
            'reg' => $row['reg'] // Don't you want the name?
          );
        }
        echo json_encode($json);

?>

我正在尝试修改本教程以使用数据库,但到目前为止我都没有成功。 http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/

在Chrome控制台中,我收到错误消息:

Port error: Could not establish connection. Receiving end does not exist.     miscellaneous_bindings:235
chromeHidden.Port.dispatchOnDisconnect

3 个答案:

答案 0 :(得分:19)

在页面上呈现选择之前,正在分配您的客户选择更改事件。将事件处理程序移动到document.ready:

<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
    $('#customer').on('change', function (){
        $.getJSON('select.php', {customerId: $(this).val()}, function(data){
            var options = '';
            for (var x = 0; x < data.length; x++) {
                options += '<option value="' + data[x]['id'] + '">' + data[x]['reg'] + '</option>';
            }
            $('#vehicle').html(options);
        });
    });
});
</script>

我还将$$('#customer')更改为$('#customer')。最后,修复SQL注入漏洞:

$sql = 'SELECT * FROM vehicles WHERE customerID = ' . (int)$id;

将ID转换为int会阻止SQLi,但您应该考虑使用Prepared Statement

您在问题中提到的错误与您的代码无关。它看起来与Chrome扩展程序相关。


不是问题的一部分,但这是一个改进的代码版本,用于构建车辆选项:

$.getJSON('select.php', {customerId: $(this).val()}, function(data){
    var vehicle = $('#vehicle');

    for (var x = 0; x < data.length; x++) {
        vehicle.append(new Option(data[x].reg, data[x].id));
    }
});

改进是:

  • 将select存储在变量中,这样我们就不必在循环的每次迭代中继续查询DOM
  • 使用new Option(...).append()创建选项并将其添加到车辆选择中。像这样构建元素比创建原始HTML更好,因为这样,您不必担心数据中的<>等字符 - 这会破坏您当前代码的HTML。
  • 您的数据被解码为Javascript对象数组,因此首选对象表示法(data[x].id)而不是data[x]['id']

答案 1 :(得分:2)

看起来好像是在select.php中的每个itteration上创建一个JSON对象数组。

下面的数组是用PHP生成的,然后是JSON编码的,这在我的选项中是最好的方法 生成JSON字符串。

// 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 += '<option value="' + data[x]['id'] + '">' + data[x]['name'] + '</option>';
    }
    $('#vehicle').html(options);
  });
});

答案 2 :(得分:2)

也许尝试live代替on。它已被弃用但我发现在未加载元素时更有可能工作。

  

$$('#customer')。on('change',function(){

更改为

  

$('#customer')。live('change',function(){