我有一个关于 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>
此代码未经测试,只是为了给您提供想法。最后检查一下并根据您的要求进行修改。
关于javascript - PHP 循环 JSON ajax 成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33082011/