腓: -
$data = array();
while($row = mysqli_fetch_array($avatar)){
$row_data = array(
'image' => $row['image']
);
array_push($data, $row_data);
}
while($row = mysqli_fetch_array($comments)){
$row_data = array(
'comment' => $row['comments']
);
array_push($data, $row_data);
}
echo json_encode($data);
jQuery Ajax: -
$(".comment").click(function(){
var id = $(this).data("id");
var name = $("#username_"+id).val();
function json(){
alert('loading please wait');
}
if(name==''){
alert("Please Fill All Fields");
}else{
$.ajax({
type: "POST",
url: "comments",
data:{comments:name,parent:id},
success: function(json){
$(".cmt_output").html(""+json["comments"]+""+json["image"]+"");
}
});
}
});
json数组格式: -
[
{"image":"1510553412_User_Avatar_2.png"},
{"comment":"Welcome"},
{"comment":"Nice"},
{"comment":"Nice"},
{"comment":"Nice too...."}
]
HTML: -
<div class="cmt_output"></div>
输出: -
undefined undefined
我希望输出:
1510553412_User_Avatar_2.png
Welcome
Nice
Nice
Nice too
答案 0 :(得分:0)
将success
功能更改为:
success: function(json)
{
json = JSON.parse(json);
json.forEach(function (item, index){
if(item.image !== undefined)
{
$(".cmt_output").append(item.image);
}
$(".cmt_output").append(item.comments);
})
}
或者代替json = JSON.parse(json);
使用:
dataType: 'json',
success: function(json)
{
json.forEach(function (item, index){
if(item.image !== undefined)
{
$(".cmt_output").append(item.image);
}
$(".cmt_output").append(item.comments);
})
}