PHP循环JSON ajax成功

时间:2015-10-12 13:10:31

标签: javascript php json ajax

我有关于在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”元素?

我的代码出了什么问题?

3 个答案:

答案 0 :(得分:3)

为什么要对最终用户低功耗PC进行过多处理。您可以在服务器端生成输出HTML并获取生成的html并将其放在html DOM中的所需位置。

您可以将PHP代码更改为:

1 var app = new EmberApp({
2   fingerprint: {
3     exclude: ['images']
5   }

现在您可以将JS更改为:

<?php
      $html = "";
      $product = mysqli_query($con,select * from product LIMIT 3);
      while ($dataproduct = mysqli_fetch_assoc($product) {
          $html .= '<li>'.$dataproduct['product'].'</li>'; 
      }
      echo $html; 
?>

现在你的html就像:

$.ajax({
type        : "GET", 
url         : test.php, 
dataType    : "html",
success     : function(data) {
             $('ul.product-list').html(data);
          }
});

此代码未经过测试,只是为了给您提供这个想法。请在最后检查并根据您的要求进行修改。

答案 1 :(得分:0)

尝试以下,它应该适合您: -

<?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>

答案 2 :(得分:0)

如果我不是完全错误,你首先必须解析JSON,不是吗?就像$ .parseJSON(数据)一样,然后你可以迭代它。

同样在outest $ .each中,您不使用键和值,但至少该值将是具有其他元素作为子元素的值。