【发布时间】:2015-01-16 14:24:03
【问题描述】:
我有一个请求新时间戳和新评论变量的评论表单。 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 将新评论添加到前面,并在隐藏的输入字段上设置新时间戳。
ajax:
<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 的数组返回。
我该怎么做?
【问题讨论】:
-
你是否在ajax调用中包含
dataType : 'json' -
你能发布 PHP 响应吗??
-
我已经更新了问题:前置有效,但每次应该显示最后一个时间戳的所有结果时只显示 1 个结果。
-
var data = jQuery.parseJSON(result);你用过这个吗??
标签: php jquery arrays ajax json