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 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上