当用户点击不同的产品数量时,我正在尝试对html表进行简单更新。虽然对jQuery很新,但我在使用ajax POST方法时遇到了一些麻烦。
这是我到目前为止所得到的:
测试table.html
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function swapContent(count){
$(".price-sidebar").html("Put animation here").show();
$.ajax({
type: "POST",
url: "myphpscript.php",
data: {countVar: count},
success: function(data){
}
});
}
</script>
</head>
<body>
<a href="#" onClick="return false" onmousedown="javascript:swapContent('18');">18</a>
<a href="#" onClick="return false" onmousedown="javascript:swapContent('48');">48</a>
<a href="#" onClick="return false" onmousedown="javascript:swapContent('96');">96</a>
<section class="price-sidebar span8" >
<h2>Price Comparison</h2>
</br>
<table class="price-data">
<tr>
<th class='store-row'><h4>Store</h4></th>
<th class='price-row'><h4>Price</h4></th>
</tr>
<!--insert returned foreach data -->
</table><!--end price-data-->
</section><!--end price sidebar-->
</body>
myphpscript.php
require('C:\wamp\www\Single-Serve-Coffee\includes\database-connect.php');
$countVar = $_POST['countVar'];
function PriceCompare($countVar){
$STH = $DBH->query('SELECT ProductID, MerchantName, Price, PageURL
FROM merchants
WHERE ProductID=677 AND Count=' . $countVar . '
ORDER BY Price');
$result = $STH->fetchAll();
foreach($result as $row){
echo "<tr>";
echo "<td class='store-row'><h5 property='seller'>" . $row['MerchantName'] . "</h5></td>";
echo "<td class='price-row'><h5 property='price'>$" . $row['Price'] . "</h5></td>";
echo "<td><a property='url' target='_blank' href='" . $row['PageURL'] . "' class='btn btn-danger'>GET IT</a></td>";
echo "</tr>";
echo "</br>";
}
}
?>
我希望foreach循环数据显示在html页面上,但我不知道如何在那里得到它。我知道我错过了成功函数,但我不知道如何编写jQuery来从我的PHP脚本调用PriceCompare()函数。
答案 0 :(得分:1)
会更好。
修改php函数,不迭代结果,只返回fetchAll返回的内容。
在PriceCompare函数中执行以下操作:
$STH = $DBH->query('SELECT ProductID, MerchantName, Price, PageURL
FROM merchants
WHERE ProductID=677 AND Count=' . $countVar . '
ORDER BY Price');
$result = $STH->fetchAll();
return $result;
php中的调用第3行中的函数如下:
$ data = PriceCompare ($ countVar);
然后返回那个json编码对象。
echo json_encode ($ data);
最终将$中的dataType:'json'放入。像这样的ajax javascript:
$. ajax ({
type: "POST",
dataType: 'json',
url: "myphpscript.php"
data: {countVar: count},
success: function (data) {
console.log(data);//iterate here the object
}
});