我试图调用mysql服务器来检索几个产品并将它们转换为表格,但它似乎并没有工作。使用AJAX和PHP进行数据检索
我只是学习服务器端,所以任何解释都会很棒,谢谢你们!
list.php的:
<?php
$pdo = new PDO('mysql:localhost:8888;dbname=searchable-db', 'pim-admin', 'admin');
$select = 'SELECT *';
$from = ' FROM `products`';
$where = ' WHERE TRUE';
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute*();
$results=$statement->fetchAll(PD0::FETCH_ASSOC);
$json=json_encode($results);
echo($json);
?>
HTML:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>AJAX Filtering</title>
<link rel="stylesheet" type="text/css" href="styles/styles.css">
</head>
<body>
<h1>Product Database</h1>
<div id="products"></div>
<table id="pieces">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Company</th>
<th>Material</th>
<th>Category</th>
<th>Style</th>
<th>Color</th>
</tr>
</thead>
</tbody>
</tbody>
</table>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function updateProducts(){
$.ajax({
type: "POST",
url: "list.php",
dataTyoe : 'json',
cache: false,
success: function(records){
$('#products').text(JSON.stringify(records, null, 4));
}
});
}
updateProducts();
function makeTable(data){
var tbl_body = "";
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k, v) {
tbl_row += "<td>"+v+"</td>";
})
tbl_body += "<tr>"+tbl_row+"</tr>";
})
return tbl_body;
}
$('#pieces tbody').html(makeTable(records));
</script>
</body>
</html>
@SmileOff,这是我现在已经到位,没有错误,但还是无法调用我的数据:/
<script>
function updateProducts(){
$.ajax({
type: "POST",
url: "includes/list.php",
success: function(records){
console.log($.parseJSON(records));
}
});
updateProducts();
function makeTable(data){
var tbl_body = "";
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k, v) {
tbl_row += "<td>"+v+"</td>";
})
tbl_body += "<tr>"+tbl_row+"</tr>";
})
return tbl_body;
}
$('#pieces tbody').html(makeTable('records'));
</script>
================= @SmileOff
JS
function updateProducts(){
$.ajax({
type: "POST",
url: "includes/list.php",
success: function(){
console.log($.parseJSON(records));
}
});
}
updateProducts();
function makeTable(data){
var tbl_body = "";
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k, v) {
tbl_row += "<td>"+v+"</td>";
})
tbl_body += "<tr>"+tbl_row+"</tr>";
})
return tbl_body;
}
$('#pieces tbody').html(makeTable('records'));
list.php的
所有的<?php
$pdo = new PDO('mysql:host=localhost:8888;dbname=searchable-db', 'pim-admin', 'admin');
$select = 'SELECT *';
$from = ' FROM products';
$where = ' WHERE TRUE';
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo($json);
?>
' - > execute *()'? 'PD0 :: FETCH'?你的代码中有一堆直接的语法错误。另外,如果不是所有其他语法错误,您的'hello word' echo只是将语法错误引入JSON代码中,否则您的代码将会生成。 – 2014-11-24 20:52:32
你的MySQL数据库实际上是否在端口8888上运行?我只问,因为这是非标准的。 – 2014-11-24 20:55:42
来访问我的数据库,我使用localhost:8888,所以我认为这是正确的链接。 – 2014-11-24 20:58:02