我有一个关于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>
这段代码没有经过测试,只是给你一个概念。在你这边检查一下,然后根据你的要求修改
如果我没有完全错误,您首先将不得不解析JSON,不是吗?比如$. parsejson (data),然后你可以遍历它。
也在最外面$。每个都不使用key和value,但至少该值将具有其他元素作为子元素。
试一下,它应该为你工作:-
<?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>