【问题标题】:Populate text field based on the selected drop down value根据选定的下拉值填充文本字段
【发布时间】:2016-03-26 04:16:42
【问题描述】:

我有以下 PHP 代码,它将查询结果(只是产品名称及其相应单价的映射)输出到 JSON 文件。 PHP 代码还会填充下拉列表。

我在创建 JSON 文件和填充下拉列表方面没有问题。我主要担心的是:

当用户从下拉列表中选择产品名称时,如何自动填充另一个文本字段以显示产品的相应单价?

<label for="p_name">Product Name</label>
<div class="input-group">
  <div class="input-group-btn">
    <input type="text" class="form-control" name="p_name" id="p_name" style="width: 300px;" required>
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span></button>
    <ul class="dropdown-menu" role="menu" style="width: 300px;">
        <?php
            $connstring = pg_connect("host=localhost dbname=myDB user=postgres password=password")
            or die('Could not connect: ' . pg_last_error());
            $select = "SELECT p_name, unit_price FROM Product";
            $executeSelect = pg_query($select) or die('Postgresql: ' . pg_last_error());

            $result = array();

            while ($line = pg_fetch_array($executeSelect, null, PGSQL_ASSOC)) {

                $index = 0;
                foreach ($line as $col_value) {
                    if ($index % 2 == 0)
                    {
                        //Display Product Name in the drop down list
                        echo "<li><a>$col_value</a></li>";
                        $index++;
                    }
                    else
                    {
                        $index++;   
                    }


                }   
                //Store query output to the result array
                $result[] = $line;

            }

            //Save the query output to a JSON file
            file_put_contents('C:\Apache\htdocs\productList.json', json_encode($result), LOCK_EX);


            pg_free_result($executeSelect);
            pg_close($connstring);                                                              
        ?>
    </ul>
  </div><!-- /btn-group -->
</div><!-- /input-group -->     


<label for="unit_price">Unit Price</label>
<input type="number" class="form-control" name="unit_price" id="unit_price"></input>

【问题讨论】:

    标签: javascript php html json


    【解决方案1】:

    使用Javascript显示产品对应的单价。

    用于在服务器上加载 JSON 文件的 JQuery。

    $.getJSON('products.json', function(data) {
        // process the data
    });
    

    有关$.getJSON()的更多信息,请查看this link

    提示:最好在文档的 onReady() 事件中加载整个 JSON 文件并填充产品名称下拉框。 根据我的经验,使用 PHP 并不是一个好的设计选择。

    【讨论】:

    • 为什么要在服务器上加载 JSON 文件? JSON文件不应该已经在客户端解析了吗?
    • JSON 文件位于 htdocs/ 文件夹中,这意味着它存在于服务器端。您只需将文件加载到客户端即可进行处理。此外,客户端对本地文件系统没有任何访问权限。
    • 谢谢,但我该怎么做呢?对不起,我对此很陌生
    猜你喜欢
    • 1970-01-01
    • 2020-03-14
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多