我需要添加一類基於時間的一些元素,而無需重新加載頁面傳遞數組與AJAX和PHP
我創建這個數組在頁面加載時。我有開始時間,結束時間和標識符。
$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>
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);
既不語言理解彼此數組類型。將您的文本轉換爲JSON格式。 PHP發送:json_encode(array);. PHP接收:json_decode(str); JavaScript發送:JSON_stringify(array);和JavaScript接收:JSON_parse(str);. – jeff
另外time.php應該與ajax調用在同一個域中,否則使用JSONP。 – reyaner
它位於同一個域中。 – Ciprian