php 使用 Ajax 填充选择框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17367332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:45:27  来源:igfitidea点击:

Using Ajax To Populate A Select Box

javascriptphpjqueryajax

提问by Iain Simpson

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 from the database, and then use the customerID to select all the vehicleID's from the database using the select.php script. What is happening is the customers box is getting selected but when the select a customer nothing happens.

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

This is my Test.php file :

这是我的 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>

This is my select.php file :

这是我的 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);

?>

I am attempting to mod this tutorial to work with the databases but so far i'm unsuccessful. http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/

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

In the Chrome console I get the error :

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

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

回答by MrCode

Your customer select's change event is being assigned before the select is rendered on the page. Move the event handler into document.ready:

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

I also changed $$('#customer')to $('#customer'). Finally, fix your SQL injection vulnerability:

我也改$$('#customer')$('#customer')。最后,修复您的 SQL 注入漏洞:

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

Casting the ID as a int will prevent SQLi here, but you should consider using a Prepared Statement.

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

The error you mentioned in the question looks unrelated to your code. It looks related to a Chrome extension.

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



Not part of the problem but here is an improved version of your code that builds the vehicle options:

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

$.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));
    }
});

The improvements are:

改进之处是:

  • Storing the select in a variable, so that we don't have to keep querying the DOM on each iteration of the loop
  • Using new Option(...)and .append()to create the options and add them to the vehicle select. Building elements like this is better than creating raw HTML because this way, you don't have to worry about characters such as <and >in the data - which would break your HTML with the current code.
  • Your data is decoded into an array of Javascript objects, so the object notation is preferred (data[x].id) instead of data[x]['id'].
  • 将选择存储在一个变量中,这样我们就不必在循环的每次迭代中不断查询 DOM
  • 使用new Option(...).append()创建选项并将它们添加到车辆选择中。构建这样的元素比创建原始 HTML 更好,因为这样,您不必担心数据中的<和等字符>- 这会用当前代码破坏您的 HTML。
  • 您的数据被解码为一组 Javascript 对象,因此首选对象表示法 ( data[x].id) 而不是data[x]['id']

回答by AlexP

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

看起来好像您在 select.php 中的每个迭代上创建了一个 JSON 对象数组。

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

下面的数组是用 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);
  });
});

回答by rebe100x

Maybe try liveinstead of on. It is deprecated but I found out is more likely to work when element is not loaded.

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

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

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

changed to

变成

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

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