dongyuchen0214 2013-07-31 07:10
浏览 30
已采纳

用ajax和php传递数组

I need to add a class to some elements based on the time without page reload

I am creating this array when the page loads. I have a start time, an end time and an identifier.

$hrs = array(
    array("2013-07-27 21:00", "2013-07-27 22:00", "one"),
    array("2013-07-27 22:00", "2013-07-27 23:00", "two"),
    array("2013-07-27 23:00", "2013-07-28 00:00", "three"),
);

Then I get the current time and grab the identifier from the array. I tried running this script in a separate file time.php using setInterval but I can't pass $hrs.

<ul>
      <li class="one">1</li>
      <li class="two">2</li>
      <li class="three">3</li>


</ul>

var className = "<?php echo $class_name"; ?>
$(className).addClass("red");

what is the proper way of running this so I won't need to refresh the page? I did something like this but it alerts error:

* Working code below ****

<script>

var hrs = '<?php echo json_encode($hrs); ?>';

//get active class from time.php
  $.ajax({
    url : 'http://domain.com/time.php',
    type : 'POST',
data : { val : hrs },
    dataType : 'json',
    success : function (result) {
       className = result['current_class'];

    },
    error : function () {
       alert("error");
    }
})

</script>

time.php

        $hrs = json_decode($_POST['val']);

    date_default_timezone_set('Europe/Bucharest');
    $date  = date('Y/m/d H:i');

    $test = strtotime($date);

    $now = date("Y-m-d H:i", $test);

    $class_name = "";
    foreach ($_POST['val'] as $h) {
    if ($h[0] <= $now and $now <= $h[1]) {
        $class_name = $h[2];fa
        break;
    }
    } 

$class = array(
        'current_class' => ( $class_name ),
    );
    echo json_encode($class);
  • 写回答

3条回答 默认 最新

  • douzai6337 2013-07-31 07:23
    关注

    Replace:

    var hrs = '<?php echo $hrs; ?>';  
    

    To:

    var hrs = '<?php echo json_encode($hrs) ?>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀