[英]jQuery AJAX POST returned data
當用戶單擊不同的產品數量時,我正在嘗試對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()函數。
如果您從php返回變量並在成功的javascript函數中迭代結果會更好。
修改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
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.