【发布时间】: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 '<input type="radio" name="product" class="product" value="'.$result['name'].'" data-price="'.$result['price'].'" />'.$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