【问题标题】:Using Ajax To Populate A Select Box使用 Ajax 填充选择框
【发布时间】:2013-06-28 14:40:03
【问题描述】:

好的,这是我在阿贾克斯的第一次尝试,它让我发疯,因为我真的无法理解它。我想做的是用数据库中的客户填充第一个框,然后使用 customerID 使用 select.php 脚本从数据库中选择所有车辆 ID。 What is happening is the customers box is getting selected but when the select a customer nothing happens.

这是我的 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).on('change', "select#customer", function(){});
  • @Brewal 为什么会这样?
  • 你能在控制台上检查一下,当项目被选中时是否建立了连接
  • 我虽然你的select#customer 是动态添加的。这将修复错误。但这种情况并非如此。控制台有错误吗?
  • 可能你的 json 语法有误。尝试将您的数据添加到数组中,然后执行echo json_encode($data); exit();

标签: javascript php jquery ajax


【解决方案1】:

在页面上呈现选择之前分配您的客户选择的更改事件。将事件处理程序移入 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));
    }
});

改进如下:

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

【讨论】:

  • 你是一个传奇!,谢谢你,我一直想知道这个周末到底发生了什么,但无法解决!谢谢!。
  • @IainSimpson 没问题 :) 查看我的编辑 - 添加了一些改进。
【解决方案2】:

看起来好像您在 select.php 中的每次迭代都创建了一个 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);
  });
});

【讨论】:

  • 小心 SQL 注入漏洞
  • @andy 谢谢。为简单起见,我只是试图回答操作员的问题。但是,这是一个有效的观点。
  • 我用新代码编辑了我的问题,但它仍然不起作用?。
  • @IainSimpson 你换了Test.php吗?
  • 是的,我更新了它们,因为它们都在上面^^,我用新代码编辑了我的问题
【解决方案3】:

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

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

改为

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

【讨论】:

    猜你喜欢
    • 2014-05-24
    • 2012-04-17
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多