使用Ajax来填充选择框 [英] Using Ajax To Populate A Select Box

查看:140
本文介绍了使用Ajax来填充选择框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,这是我在阿贾克斯的第一个尝试,它让我疯狂,我真的不能让我的头轮它。什么即时要做的是填充从数据库中客户的第一个框,然后使用在客户选择所有的vehicleID的使用该select.php脚本的数据库。 正在发生的事情是在客户中是越来越选中,但在选择客户没有任何反应。

这是我的test.php文件:

 < PHP的包括'connectmysqli.php; ?>
    < HTML>
        < HEAD>
            < META HTTP-当量=内容类型内容=text / html的;字符集= UTF-8>
            <冠军>选择测试< /标题>
        <脚本SRC =./ JS / jQuery的/ jquery.js和>< / SCRIPT>
            <脚本类型=文/ JavaScript的字符集=utf-8>
    $$('#客户)。在('改变',函数(){
      $ .getJSON('select.php',{客户ID:$(本).VAL()},功能(数据){

        VAR的选择='';
        为(变种X = 0 X  - 其中; data.length; X ++){
          选项​​+ ='<期权价值=+数据[X] ['身份证'] +'> +数据[X] ['章'] +'< /选项>';
        }
        $('#车辆)HTML(选项)。
      });
    });
            < / SCRIPT>
        < /头>
        <身体GT;
            <选择一个id =客户>
            < PHP
    $ SQL =<<< SQL
    选择 *
    从`客户`
    SQL;
    如果($结果= $ DB->!查询($的SQL)){死(有运行查询错误['$ DB->错误']');}
    而($行= $ result-> FETCH_ASSOC()){
    如果($行['bussinessname'] ==''){$名称= $行['标题'。 '。$名字= $行['名字'。 '。$名字= $行['姓'];}其他
    {$名称= $行['bussinessname'];}
    回声'<期权价值='。$行['的customerID'。'>'$名字。< /选项>';
    }
    回声'< /选择>< / P>';
            ?>
            < /选择>
            <选择ID =车>
            < /选择>
        < /身体GT;
    < / HTML>
 

这是我的select.php文件:

 < PHP的包括'connectmysqli.php; ?>
    < PHP
    的$ id = $ _GET ['客户ID'];
    $ SQL =SELECT * FROM WHERE车辆的customerID ='。 $ ID;
    $结果= $ DB->查询($ SQL);

    $ JSON =阵列();
    而($行= $ result-> FETCH_ASSOC()){
      $ JSON [] =阵列(
        'ID'=> $行['vehicleID'],
        '章'=> $行['章'] //不要你想叫什么名字?
      );
    }
    回声json_en code($ JSON);

    ?>
 

我试图mod本教程的数据库的工作,但到目前为止,我是不成功的。 的http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/

在Chrome的控制台我得到的错误:

 端口错误:无法建立连接。接收端不存在。 miscellaneous_bindings:235
chromeHidden.Port.dispatchOnDisconnect
 

解决方案

您的客户选择的改变事件被分配之前,选择页面上的呈现方式。将事件处理成的document.ready:

 <脚本类型=文/ JavaScript的字符集=utf-8>
$(文件)。就绪(函数(){
    $('#客户)。在('改变',函数(){
        $ .getJSON('select.php',{客户ID:$(本).VAL()},功能(数据){
            VAR的选择='';
            为(变种X = 0 X  - 其中; data.length; X ++){
                选项​​+ ='<期权价值=+数据[X] ['身份证'] +'> +数据[X] ['章'] +'< /选项>';
            }
            $('#车辆)HTML(选项)。
        });
    });
});
< / SCRIPT>
 

我也改变了 $$('#客户') $('#客户')。最后,解决您的SQL注入漏洞:

  $ SQL =SELECT * FROM WHERE车辆的customerID ='。 (INT)的$ id;
 

铸造的ID为INT将在这里prevent SQLI,但你应该考虑使用 prepared声明

你的问题中提到的错误看起来无关的code。它看起来涉及到一个Chrome扩展。


不是问题的一部分,但这里是你的code的改进版本,建立车辆选项:

  $的getJSON('select.php',{客户ID:$(本).VAL()},功能(数据){
    变种车= $('#车');

    为(变种X = 0 X  - 其中; data.length; X ++){
        vehicle.append(新选件(数据[X]的.reg,数据[X] .ID));
    }
});
 

的改进是:

  • 存储选择在一个变量,这样我们就不必继续查询DOM在每次循环
  • 使用新的选项(...) .append()以创建选项并将其添加到车辆选择。像这样的建筑元素比创建原始的HTML,因为这种方式比较好,你不用担心的字符,如< > 中的数据 - 这将打破你的HTML与当前code
  • 您的数据是德codeD插入Javascript对象的数组,所以对象符号是preferred(数据[X] .ID ),而不是数据[X] ['身份证']

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.

This is my Test.php file :

                    <?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 :

                    <?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/

In the Chrome console I get the error :

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

解决方案

Your customer select's change event is being assigned before the select is rendered on the page. Move the event handler into 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:

$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.

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


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'].

这篇关于使用Ajax来填充选择框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆