php - 使用ajax更新HTML输入

标签 php jquery html mysql ajax

我们有一个数据库:

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'];
}

用户选择它,现在如何用产品的价格更新价格输入?

最佳答案

您的“search.php”应返回价格和 html 的 json

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

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

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

关于php - 使用ajax更新HTML输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25352619/

相关文章:

css - HTML/CSS - 在 Div 中水平滚动图像

php - 页面速度因循环而变慢

php - 使用 preg_match 检查字符串的结构

php - 调用成员函数 ERROR PHP

javascript - 将 KeyParam 替换为动态 JSON - 继续问题 - 57833909

javascript - 当包含页面处于怪癖模式时,iframe 不在 ie9 模式下呈现

php - 为什么页面仅在首页加载时才获取 undefined variable ?

javascript - Jquery val() 无法读取 php echo 接收到的 html 标签

javascript - 使用 Google Maps API v3 重新加载 map 上的点

jquery - 使用 e.latedTarget 从 <a> 获取数据到模态有时会给出未定义的结果