【问题标题】:HTML input update with ajax使用 ajax 更新 HTML 输入
【发布时间】:2014-10-10 17:39:25
【问题描述】:

我们有一个数据库:

ID    Name     Price
1   product1    200
2   product2    300
3   product3    400

还有我的表格:

<form action="test.php" method="post" />
<input type="text" name="search" id="search" placeholder="enter name product" />
<div id="result">display result form ajax</div>
<label>price</label>
<input type="text" name="price" id="price" readonly" />
<input type="submit" name="submit" />
</form>

js 文件:

// Start Ready
$(document).ready(function() {  

    // Icon Click Focus
    $('div.icon').click(function(){
        $('input#search').focus();
    });

    // Live Search
    // On Search Submit and Get Results
    function search() {
        var query_value = $('input#search').val();
        $('b#search-string').html(query_value);
        if(query_value !== ''){
            $.ajax({
                type: "POST",
                url: "search.php",
                data: { query: query_value },
                cache: false,
                success: function(html){
                    $("ul#results").html(html);
                }
            });
        }return false;    
    }

    $("input#search").live("keyup", function(e) {
        // Set Timeout
        clearTimeout($.data(this, 'timer'));

        // Set Search String
        var search_string = $(this).val();

        // Do Search
        if (search_string == '') {
            $("ul#results").fadeOut();
            $('h4#results-text').fadeOut();
        }else{
            $("ul#results").fadeIn();
            $('h4#results-text').fadeIn();
            $(this).data('timer', setTimeout(search, 100));
        };
    });

});

当用户在搜索输入中搜索名称产品时(我们向 search.php 发送 ajax 请求并显示类似该关键字的产品) 搜索.php:

connection db and other code...
if(product) {
echo '<input type="radio" name="product" id="product" value="'.$result['name'].'" />'.$result['name'];
}

并且用户选择了那个,现在如何用产品的价格更新价格输入?

【问题讨论】:

  • 您可以在data 属性中添加价格 -> echo '&lt;input type="radio" name="product" class="product" value="'.$result['name'].'" data-price="'.$result['price'].'" /&gt;'.$result['name'];。然后在你的 js 代码中,$('ul#results').on('click', '.product', function(){ $('#price').val($(this).data('price')); });。请注意,您的每个单选按钮都会有 id="product",这会创建无效的 html,所以我更改为 class="product" 以在 js 中使用 -> '.product'
  • 谢谢。它成功了,还有一个问题是这样获取数据是否安全(我的方式)?
  • 不确定您所说的安全是什么意思。您的代码看起来不错。只要您在搜索数据库时正确清理数据,就可以了,因为您提供的只是connection db and other code...

标签: php jquery html mysql ajax


【解决方案1】:

你的'search.php'应该返回价格和html的json

{
    price: 200,
    html: "......"
}

在成功功能中,您可以更新价格

success: function(json){
    $('#price').val(json.price);
    $("ul#results").html(json.html);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-15
    • 2014-11-24
    • 2020-04-26
    • 2014-11-06
    • 2015-07-13
    • 1970-01-01
    • 2012-09-25
    • 2018-11-24
    相关资源
    最近更新 更多