While you can pass a PHP array to a JavaScript function,你可以通过反面吗? (将JavaScript函数转换为PHP数组)。
考虑这段代码。我想在PHP数组中调用一个JavaScript计时器,因为该数组随后将消息随机化为一个echo。
$messages = array('How are you today?', 'Perfect day for flying, isnt it?', 'You have flown last on '.$lastflown.'.', 'The time is /* insert the JavaScript function to call a timer here */');
$key = array_rand($messages);
当然我想要显示消息:
<?php echo $messages[$key]; ?>
这可能吗?如果没有,怎么能绕过这个?也许是一个JavaScript随机化器呢?
答案 0 :(得分:1)
也许这段代码可以帮助你。
$messages = array('How are you today?', 'Perfect day for flying, isnt it?', 'You have flown last on '.$lastflown.'.', 'The time is <script> document.write(new Date().toString());</script>');
$key = array_rand($messages);
<?php echo $messages[$key]; ?>
您需要使用代码包围JavaScript代码。要显示JavaScript输出,请使用document.write()函数。
此字符串'The time is <script> document.write(new Date().toString());</script>'
将在浏览器中显示为The time is Wed Oct 21 2015 17:18:32 GMT+0300 (MSK)
。