php - 使用ajax和php传递数组

标签 php jquery ajax

我需要根据页面重新加载的时间向某些元素添加类

我在页面加载时创建这个数组。我有开始时间、结束时间和标识符。

$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"),
);

然后我获取当前时间并从数组中获取标识符。我尝试使用 setInterval 在单独的文件 time.php 中运行此脚本,但无法传递 $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");

运行此程序的正确方法是什么,这样我就不需要刷新页面?我做了类似的事情,但它警告错误:

* 下面的工作代码****

<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>

时间.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);

最佳答案

如果您使用POST发送数据

type : 'POST',

您必须使用 $_POST 访问它,您正在使用 $_GET

$_POST['val']

关于php - 使用ajax和php传递数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17963846/

相关文章:

php - 如何在 QT/C++ 中解压缩在 PHP 中压缩的数据 (gzcompres)

php - 特定页面的 apache 重写规则问题

php - 通过数组变量索引php数组

可调整大小的 jQuery UI 停止工作

jquery - Bootstrap jquery 如何对齐从 jquery 添加的图像

javascript - Jquery 在 AJAX 表单结果显示中没有响应

php - WordPress ACF : How to add rows to a repeater field attached to a user via custom code (PHP)

javascript - masonry 网格连续循环滚动

ios - 来自 native 移动应用程序的 AJAX 请求

javascript - 使用 jQuery 获取给定目录中的文件名