【发布时间】:2015-10-19 17:54:44
【问题描述】:
这个问题更多的是关于“良好实践”而不是真正的问题;我刚开始使用 php 和 jquery,但我会更详细地了解我在做什么以及为什么。
我想要得到什么:捕获用户请求(使用表单),查询数据库,然后在表格中显示结果。全部使用ajax调用和jquery。
现在,我有了我的 controller.php:
class Controller {
public $model;
public function __construct() {
$this->model = new Model ();
}
public function run() {
$action = isset ( $_REQUEST ["action"] ) ? $_REQUEST ["action"] : $action = "home";
switch ($action) {
case "home" :
//doing stuff
break;
case "search" :
//this function will take arguments then perform a query and return results.
$result = $this->search();
//I put $result into a $prod field of my model.
$this->model->prod = $result;
//then I would display acquired data into a table.
echo include 'view/include/result-table.php';
break;
}
}
function search() {
//query DB etc..
}
}
这是我的表格 (view/include/result-table.php),我想将它插入到我页面的 div 中。
<?php
if (isset ( $this->model->prod )) {
if (count ( $this->model->prod ) == 0) {
echo "<h4 class=\"info\"> No product find";
} else {
?>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Descr</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<?php
foreach ( $this->model->prod as $p ) {
echo "<tr><td> $p->id </td>";
echo "<td>" . ucfirst ( $p->name ) . "</td>";
echo "<td>" . ucfirst ( $p->descr ) . "</td>"
// and so on..
}
?>
</tbody>
</table>
<?php
}
}
?>
问题 1:"echo include "view/include/....php" 似乎也在页面末尾(或 div)回显 1(一个数字)。为什么?
“问题 2”:这工作得很好,但我不确定这是正确的方法。是否有任何其他解决方案可以查询数据库并在 div 中显示结果,只有 jquery/ajax 请求? (我不希望每次都刷新页面)。也许可以加快响应速度和/或提高安全性。
非常感谢!
【问题讨论】: