【问题标题】:Show html dropdown list according chosen options根据选择的选项显示 html 下拉列表
【发布时间】:2013-05-18 09:58:23
【问题描述】:

我正在构建一个使用 python CGI 查询数据库的小型 Web 应用程序。逻辑是: HTML 表单 - Python CGI - SQL 查询 - python cgi 打印结果。

目前它可以工作,但现在我无法创建表单。我想要做的是根据第一个表格的结果自动填写第二个表格。示例:

第一个下拉选项:汽车、摩托车、公共汽车、火车。
第二个下拉菜单:如果我选择汽车,则只播种汽车选项。如果火车,只有火车选项...

我知道如何使用SQL ('WHERE type = 'car'') 制作,但我不知道如何填写 html 表单。

我没有使用任何框架,只使用了 HTML、Python(而不是 php)和 Postgresql

【问题讨论】:

    标签: python html sql cgi


    【解决方案1】:

    您必须使用 ajax:当第一个选择发生变化时,您必须将所选值传递给处理请求并将结果返回到页面的远程 python 脚本:此时必须通过 javascript 填充第二个选择。
    数据可以是简单的 html 或 json 格式。 这是一个使用 jquery 和 ajax 的示例(记得包含 jQuery library):
    html:

    <form action="" method="post">
        <select class="changeStatus" name="changeStatus">
                <option value="0">Car</option>
                <option value="1">Motorcycle</option>
                <option value="2">BUS</option>
        </select>
    
    </form>
    

    javascript:

    <script>
    $('document').ready(function(){
    //  change event handler
    $('select.changeStatus').change(function(){
        // You can access the value of your select field using the .val() method
        //alert('Select field value has changed to' + $('select.changeStatus').val());
        // You can perform an ajax request using the .ajax() method
        $.ajax({
              type: 'GET',
              url: 'your_script_python.py', // This is the url that will be requested
    
              // select value available inside your_script_python.py
              data: {selectFieldValue: $('select.changeStatus').val()},
    
              // on success: populate your second select.
              success: function(html){ 
                alert('data passed: ' + html);
               },
              dataType: 'html' // or json 
        });
    
    });
    });
    </script>
    

    【讨论】:

    • 我知道还有一些“超越”SQL、HTML 和 Python 的东西。我是一个新手程序员,我没有任何 Ajax 经验,但是,现在,我知道我需要阅读哪些教程。谢谢你的例子!
    猜你喜欢
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    相关资源
    最近更新 更多