如何使用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 while循环打印到#post
答案 0 :(得分:0)
您需要将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>
祝你好运