php/print out json php while loop


php/print out json php while loop

如何使用 JSON 从 while 循环中打印出数据?

目前,我在message.php

        <script type="text/javascript">
        $('#pmid<?php echo $convoData['id']; ?>').click(function(){
            $.ajax({
                 type:"GET",
                 url: "/index.php?i=pm&p=rr",
                 dataType:'json',
                 data: {id:"<?php echo $convoData['id']; ?>"},
                 success : function(res){
                   if(res){
                    $( "#name").html(res.name); 
                    $( "#post").html(res.response);
                   }
                 }
            });
          });
        </script>
<span id="name"></span>
                <ul id="post">
                </ul>

get.php文件中,我有这个:

$name=$getUser['username'];

while($postData=mysql_fetch_assoc($postsql)){
 $post = '<li>
   <img width="30" height="30" src="images/avatar-male.jpg">
   <div class="bubble">
     <a class="user-name" href="">123</a>
     <p class="message">
       '.$postData['text'].'
     </p>
     <p class="time">
     </p>
   </div>
 </li>';
}
$arrRet = array();
$arrRet['name'] = $name;
$arrRet['post'] = $post;
echo json_encode($arrRet); 
die();

到目前为止,$name值正在发挥作用。我可以把它打印出来#name.我只是不知道如何在循环中打印出$post #post

您需要将MySQL结果添加到数组中,然后使用此创建json

然后在 JavaScript 代码中,使用 for/foreach 循环打印数据(post)

您的Get.php应该像这样:

$name=$getUser['username'];
$result = array();
while($postData=mysql_fetch_assoc($postsql)){
    $result[] = $postData['text'];
}
$arrRet = array();
$arrRet['name'] = $name;
$arrRet['post'] = $result;
echo json_encode($arrRet);
die();

message.php

        <script type="text/javascript">
        $('#pmid<?php echo $convoData['id']; ?>').click(function(){
            $.ajax({
                 type:"GET",
                 url: "/index.php?i=pm&p=rr",
                 dataType:'json',
                 data: {id:"<?php echo $convoData['id']; ?>"},
                 success : function(res){
                   if(res){
                    $( "#name").html(res.name); 
                    var posts = res.post;
                    for(var i in posts)
                    {
                        var post = '<li><img width="30" height="30" src="images/avatar-male.jpg"><div class="bubble">
                                    <a class="user-name" href="">123</a><p class="message">'
                                    + posts[i] +
                                    '</p><p class="time"></p></div></li>';
                        $( "#post").append(post);
                    }
                   }
                 }
            });
          });
        </script>
<span id="name"></span>
      <ul id="post">
      </ul>

祝你好运