使用Ajax填充选择框

Using Ajax To Populate A Select Box

本文关键字:选择 填充 Ajax 使用      更新时间:2023-09-26

好吧,这是我第一次尝试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

在页面上呈现选择之前,将分配客户选择的更改事件。将事件处理程序移到文档中。准备:

<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语句。

您在问题中提到的错误看起来与您的代码无关。它看起来与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']

看起来就像是在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);
  });
});

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

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

更改为

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