[英]PHP Loop JSON ajax success
我對在ajax成功時循環遍歷json輸出有問題。 這是我的代碼:
<?php
$product = mysqli_query($con,select * from product LIMIT 3);
while ($dataproduct = mysqli_fetch_assoc($product) {
echo json_encode(array(
"product" => $dataproduct['product']
));
}
?>
$.ajax({
type : "GET",
url : test.php,
dataType : "json",
success : function(data) {
$.each(data, function() {
$.each(this, function(k, v) {
$("ul").html(data.product);
});
});
}
});
<ul>
<li></li>
</ul>
如何使“ ajax成功循環。”以便我可以將輸出輸出到“ ul”元素?
我的代碼有什么問題?
為什么要在最終用戶低功耗PC上保留過多的處理。 您可以在服務器端生成輸出HTML,並獲取結果html並將其放在html DOM中的所需位置。
您可以將您的PHP代碼更改為以下代碼:
<?php
$html = "";
$product = mysqli_query($con,select * from product LIMIT 3);
while ($dataproduct = mysqli_fetch_assoc($product) {
$html .= '<li>'.$dataproduct['product'].'</li>';
}
echo $html;
?>
現在,您可以將JS更改為以下內容:
$.ajax({
type : "GET",
url : test.php,
dataType : "html",
success : function(data) {
$('ul.product-list').html(data);
}
});
現在,您的html可以像這樣:
<ul class="product-list">
<!-- Insert Products here -->
</ul>
此代碼未經測試,僅是為了給您提供想法。 在您的末端檢查並根據您的要求進行修改。
嘗試以下操作,它應該適合您:-
<?php
$product = mysqli_query($con,select * from product LIMIT 3);
$temp = array();
while ($dataproduct = mysqli_fetch_assoc($product) {
$temp[] = $dataproduct['product'];
}
echo json_encode($temp);
?>
$.ajax({
type : "GET",
url : test.php,
dataType : "json",
success : function(data) {
$.each(data, function(k,v) {
$("ul").html(v);
});
});
}
});
<ul>
<li></li>
</ul>
如果我不是完全不正確,那么您一開始就必須解析JSON,不是嗎? 就像$ .parseJSON(data)一樣,然后您可以對其進行迭代。
同樣,在最遠的$ .each中,您不使用鍵和值,但至少該值將是具有其他子元素的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.