因此,当客户端上的用户从下拉列表中选择一个项目时,应该显示一个包含查询结果的新div容器。我遇到的问题是div容器按预期弹出,但没有包含查询搜索结果的标记。
兴趣点
data.php
<?php
if(!isset($_GET['name'])) die('A vitamin name is required.');
require '../vitamins.php';
$pdo = new PDO('mysql:host=localhost;dbname=vitamins', 'root', 'root');
$table = new Vitamins($pdo);
$param = $_GET['name'];
$data = $table->getData($param);
?>
<div class="row">
<?php while($data): ?>
<?php $i = 0;
while($i < 3){ ?>
<div class="column">
<h1><?php print $data['name']; ?></h1>
<p>serving</p>
<p><?php print $data['grams']; ?>G = <?php print $data['percentage']; ?>%</p>
</div>
<?$i++;
}?>
<br/>
<?php endWhile; ?>
查询方法vitamin.php
<?php
class Vitamins {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
public function getAll()
{
return $this->db->query('SELECT * FROM vitamins');
}
public function getData($name) {
$nameEscaped = $this->db->quote($name);
$sql = "SELECT 'v'.'name', 'f'.'name', 'p'.'grams', 'p'.'percentage', 'i'.'path' " .
"FROM 'vitamins' 'v' JOIN 'percentage' 'p' ON 'v'.'id' = 'p'.'vitamin_id' " .
"JOIN 'food' 'f' ON 'f'.'id' = 'p'.'food_id' " .
"JOIN 'images' 'i' ON 'i'.'id' = 'f'.'image_id' " .
"WHERE 'v'.'name' = {$nameEscaped}";
return $this->db->query($sql);
}
}
index.php中的脚本
<script>
$(function() {
var trans = $('.transbox');
var lower = $('.containerL');
$('.dropdown li').click(function(e) {
e.preventDefault();
var name = $(e.target).html();
$.get('./vitamins/data.php', { name: name }, function(data) {
console.log(data);
trans.html(data);
trans.show();
});
lower.hide();
console.log('clicked');
console.log(trans, lower);
});
});
</script>