douwen9540 2015-11-06 19:22
浏览 32
已采纳

如何在PHP上使用AJAX检索MySQL值?

Ok, this one is taking me some time now, I've read other topics and cannot seem to solve it.

I have a select populated with a PHP function article_search() that retrieves all article names from a the table article in my DB

<select id="article_select">
    <?php
        $article_group = article_search();
        foreach($article_group as $item) {
            echo "<option value=\"{$item["idArt"]}\">{$item["name"]}</option>";
        }
    ?>  
</select>

What I need is, when the user selects an article, an AJAX function search the field price from the table article in the database and puts the result in this element:

<p>Price:
    <input type="text" class="details" id="price" name="price">
</p>

Needless to say that I have no experience in AJAX, but it seems like the only solution at these point.

Every bit of help would be appreciated.

  • 写回答

2条回答 默认 最新

  • dongzen5577 2015-11-07 00:32
    关注

    Personally, I would put the price in the the original options:

    <select id="article_select">
        <?php
            $article_group = article_search();
            foreach($article_group as $item) {
                echo "<option value=\"{$item["idArt"]}\" price=\"{$item['price']}\">{$item["name"]}</option>";
            }
        ?>  
    </select>
    

    Then, you can collect this using JQuery like so (http://jsfiddle.net/Twisty/6unsdztu/):

    $(document).ready(function(){
        $("#article_select").change(function(){
            var price = $(this).find("option:selected").attr("price");
            var $inp = $('<input />',{
                type: "text",
                class: "details",
                id: "price_" + $(this).val(),
                name: "price",
                value: price
            });
            var $p = $('<p />');
            $p.append("<label>Price:</label>", $inp);
            $p.appendTo("#price_form");
        });
    });
    

    This seems like a bad idea overall. The user could try to manipulate the price if you're passing it back to the Database, unless they get a chance to negotiate the price.

    Since the Price is in the DB, why bring it out to a text field? he end, if this is a shopping cart, we just need to know which items are in the cart, and we can calculate a total later or as we go. Hopefully the above example fits what you need. If not, comment or edit your post with more details.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line