繁体   English   中英

使用Ajax填充选择框

[英]Using Ajax To Populate A Select Box

好吧,这是我对阿贾克斯的第一次尝试,它让我疯狂,因为我真的无法理解它。 我想要做的是从数据库填充客户的第一个框,然后使用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

在页面上呈现选择之前,正在分配您的客户选择更改事件。 将事件处理程序移动到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']

看起来好像是在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(){

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM