我有一个请求新时间戳和新评论变量的评论表单。 newtimestamp 变量是单个变量,newcomment 变量是从 foreach 循环返回的数组。
ajaxrequest.php:
foreach ($array2 as $print2) {
$var1 = $print2['var'];
$newtimestamp = $now;
$newcomment = "<div class=post>$var1</div>";
echo json_encode(array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment));
}
然后,我使用 ajax 在新注释前面加上新注释,并在隐藏的输入字段上设置 newtimestamp。
阿贾克斯:
<script>
$(document).ready(function(){
$('#commentform').on('submit',function(e) {
$.ajax({
url:'ajaxrequest.php',
data:$(this).serialize(),
type:'POST',
dataType: 'JSON',
success:function(data, response){
$("#posts").fadeOut(300);
$("#posts").prepend(data.newcomment);
$("#time").val(data.newtimestamp);
$("#posts").fadeIn(500);
$('html, body').animate({ scrollTop: $('#posts').offset().top - 100 }, 'fast');
console.log(data);
},
error:function(data){
console.log(data);
}
});
e.preventDefault();
return false;
});
});
上面的方法在控制台中给了我一条成功消息,前置有效,但每次只显示 1 个结果,而它应该显示最后一个时间戳的所有结果。 如果用户发布第二条、第三条等评论,则隐藏输入字段的前置和设置值不起作用。
安慰:
Object {newtimestamp: "2014-11-19 07:59:48", newcomment: "<div>a new comment</div> 1"}
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
我需要将 newtimestamp 变量作为单个变量(而不是数组)返回,并将其设置为隐藏的输入字段值,并且我需要将 newcomment 变量作为可以附加到div 的数组返回。
我该怎么做?
更改您的 php 文件。我不确定这是你期待的。
ajaxrequest.php:
foreach ($array2 as $print2) {
$var1 = $print2['var'];
$newtimestamp[] = $now;
$newcomment[] = "<div class=post>$var1</div>";
}
echo json_encode(array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment));
像这样重写你的 php 代码
$data = array();
foreach ($array2 as $print2) {
$var1 = $print2['var'];
$newtimestamp = $now;
$newcomment = "<div class=post>$var1</div>";
$data['data'][] = array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment);
}
echo json_encode($data);
现在 JSON 响应将如下所示
{"data" : [{"newtimestamp" : 72345654,"newcomment" : "comment data"},{"newtimestamp" : 72345654,"newcomment" : "comment data"}]}
使用 jQuery each
遍历对象数组。最终代码将如下所示。
$.each($response.data,function(index,value){
$("#posts").prepend(value.newcomment);
$("#time").val(value.newtimestamp);
})
注意:发送application/json
标头(以便默认情况下将响应解析并转换为js对象)或在接收后对其进行解析。此操作应在each
循环之前发生
那是因为你正在回显多个JSON字符串。您需要回显包含所有数据的单个 JSON 字符串。
尝试下面的代码,这对我有用。你只需要把它放到你的jQuery和PHP代码中。
<?php
$jsonArray = array();
$array2 = array(array('var'=>1),array('var'=>2));
foreach ($array2 as $print2)
{
$var1 = $print2['var'];
$newtimestamp = time();
$newcomment = "<div class=post>$var1</div>";
$jsonArray[] = array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment);
}
print_r($jsonArray);
$data = json_encode($jsonArray);
?>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
var data = jQuery.parseJSON('<?=$data?>');
$.each(data, function(item, value){
console.log(value['newtimestamp']);
});
</script>