【问题标题】:ajax return single variable and an array variableajax 返回单个变量和一个数组变量
【发布时间】: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


【解决方案1】:

那是因为你在回显多个 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>

【讨论】:

    【解决方案2】:

    像这样重写你的 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 循环之前

    【讨论】:

      【解决方案3】:

      更改您的 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));
      

      【讨论】:

      • 这将返回一个像{"newtimestamp" : ["data","data","data"],"newcomment" : ["data","data","data"]}这样的json字符串,在我看来这不是一个好主意。
      猜你喜欢
      • 2018-05-18
      • 1970-01-01
      • 2018-09-19
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 2014-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多