我创建了一个过滤器表单
,当我提交该表单时,它会向give_results_json.php
发送一个ajax请求,然后在后端give_results_json发送。 php
对数据库进行查询并以 JSON
格式返回数据。
方法1
give_results_json.php
$rows = $pdo->query($query);
echo json_encode($rows);
返回数据
[{"title":"Top Class home",,"cnt_rooms":3,"floor":1,"square_living":372},{"title":"Home of Dreams",,"cnt_rooms":4,"floor":2,"square_living":374}....]
然后我用 jQuery 处理这些数据,以 HTML 形式显示数据
json数据由Jquery在前端处理
function property_str(value_obj){
return '<div class="property-container"><div><<div class="detail"><div class="fig-title clearfix"><h3>'+value_obj.title+'</h3></div><ul><<li>'+value_obj.cnt_rooms+' Rooms</li><li>'+value_obj.square_living+' Sq Ft</li></ul></div></div>';
}
$('#filter_form').on("submit",function(e){
e.preventDefault();
$.ajax({
type: 'get',
url: "give_results_json.php",
data: $(this).serialize(),
success: function(data){
json_obj = $.parseJSON(data);
var result_str =''
$.each(json_obj, function(index,value){
result_str += property_str(value)
});
$("#filter_results").html(result_str)
}});
});
以上方法是否正确,或者最好在后端处理数据并返回HTML结果,然后javascript只需将该数据附加到页面
因此give_results_json.php
将变为give_results_html.php
方法2
give_results_html.php
$rows = $pdo->query($query);
foreach($rows as $row){
$complete_html_str .= '<div class="property-container"><div><<div class="detail"><div class="fig-title clearfix"><h3>'.$row['title'].'</h3></div><ul><<li>'.$row['cnt_rooms'].' Rooms</li><li>'+$row['square_living']+' Sq Ft</li></ul></div></div>';
}
echo $complete_html_str;
返回数据
<div class="property-container"><div><<div class="detail"><div class="fig-title clearfix"><h3>Top Class home</h3></div><ul><<li>3 Rooms</li><li>'+374 Sq Ft</li></ul></div></div><div>...........
可以通过Jquery在前端轻松处理
$.ajax({
type: 'get',
url: "give_results_json.php",
data: $(this).serialize(),
success: function(data){
$("#filter_results").html(data)
}});
注意:实际上,从数据库返回的数据要多得多,大约有 20 列,但我需要一次获取 20 行数据
谢谢!
最佳答案
我想说方法 2 是错误的,因为它返回 VIEW 层(HTML 标记)。情况不应该如此。您应该将数据与 View 分开。方法2不这样做。方法 1 更好,尽管我也将方法更改为使用 jquery 对象创建而不是返回纯 html。现在看起来 property_str
实际上正在用数据填充模板。这是有效且可读的,但并没有真正被认为是“jquery 方式”。
关于javascript - 以 json 或 html 形式返回数据库结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51746151/