doutu3352 2017-04-05 08:48
浏览 39
已采纳

测量json_encode的时间并将json对象和计时器返回给AJAX

I need to measure the time of a json_encode operation and then return the value together with the json object without decoding it. How can I make this happen?

The code I have at the moment is:

$start2 = microtime(true);
$all = json_encode(array(iterator_to_array($cursor),$timeExecuted));
$end2 = microtime(true);
$result = ($end2-$start2);
echo $all;

How can I return $all and $result without decoding the json object?

  • 写回答

2条回答 默认 最新

  • douwei1944 2017-04-05 09:04
    关注

    Your problem is that you're trying to send a JSON response to the client but include in that JSON response the time it took to generate the response. That's kind of impossible, but you then approximate it by including the time it took to generate the response but excluding the time it took to generate the time it took to generate the response (more realistic).

    I think the simplest solution would be:

    $start2 = microtime(true);
    $all = json_encode(array(iterator_to_array($cursor),$timeExecuted));
    $end2 = microtime(true);
    $result = ($end2-$start2);
    echo json_encode(["all" => $all, "result" => $result ]);
    

    However in the client side you now need to do:

    success: function (data) {
         var all = JSON.parse(data.all);
         var time = data.result; 
    }
    

    You could also do some sort of botch fix which may or may not work like:

    ...
    echo "[" . json_encode($result). ", ". $all . "]";
    

    Then you can access result like:

    success: function (data) {
           var time = data[0];
           var all = data[1];
    }
    

    Beware when you use the 2nd way. It's generally bad practice because of odd encoding issues that may come up. Here it should be ok because $result is a number, but in general, it's not the best solution.

    Note: Don't forget to set content headers before echoing anything, this will tell AJAX that it received a JSON response and will parse it accordingly:

     header("Content-Type: text/json");
    

    3rd solution which may or may not work (not tested):

    $start2 = microtime(true);
    $all = json_encode(array(iterator_to_array($cursor),$timeExecuted));
    $end2 = microtime(true);
    $result = ($end2-$start2);
    header("Content-Type: text/json");
    header("X-Encoding-Time: ".$result);
    echo $all;
    

    And in your AJAX:

    success: function (data, textStatus, request) {
          var all = data;
          var result = request.getResponseHeader("X-Encoding-Time");
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗