2013-10-24 23 views
-1

如何使用JSON打印出while循环中的数据?php/json - 打印出循环中的json php

目前,我有这样的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。我只是无法弄清楚如何打印出$后while循环#post

+4

如果你要downvote你能做的就是发表评论,并解释自己要去哪里错了OP最少的! – Paddyd

+0

@Paddyd,我在另一个SO组中提出了这个问题。我因为存在而被低估了,唯一的解释是,下流者喜欢匿名,并且不会提供任何帮助。 – jeff

回答

0

您需要与此

然后添加你的MySQL结果到一个数组,然后使JSON在JavaScript代码,你将打印数据(后)与用于/ foreach循环

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> 

好运