php - 将 JavaScript 函数转换为 PHP 函数

标签 php javascript

我想将这段 JavaScript(可以正常工作)转换为 PHP 函数,这样所有这些代码就不必出现在网页的源代码中。

<script type="text/javascript">

    var images = [],
    index = 0;

    images[0] = "<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>";

    images[1] = "<a href = 'http://www.random_target2.com' target='_blank'><img src='//www.random_target2.com/random_banner.jpg' width='120' /></a>";

    images[2] = "<a href = 'http://www.random_target3.com' target='_blank'><img src='//www.random_target3.com/random_banner.jpg' width='120' /></a>";

    index = Math.floor(Math.random() * images.length);
    document.write(images[index]);

</script>

我在 PHP 文件中尝试了这个 PHP 函数,并认为我可以从 HTML 文件中调用它的结果,因此只有确定的值才会出现在 HTML 源代码中。不过,这段代码破坏了页面。

public function getRandom()
{
    $images = array();
    $index = 0;

    $images[0] = "<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>";

    $images[1] = "<a href = 'http://www.random_target2.com' target='_blank'><img src='//www.random_target2.com/random_banner.jpg' width='120' /></a>";

    $images[2] = "<a href = 'http://www.random_target3.com' target='_blank'><img src='//www.random_target3.com/random_banner.jpg' width='120' /></a>";

    $index = Math.floor(Math.random() * $images.length);
    return $images[$index];
}   

最佳答案

$images = array(
"<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>",
 "<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>",
 "<a href = 'http://www.random_target1.com' target='_blank'><img src='//www.random_target1.com/random_banner.jpg' width='120' /></a>"
);
$index = rand(0, count($images)-1);

echo $images[$index];

关于php - 将 JavaScript 函数转换为 PHP 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8786326/

相关文章:

php - 从 Laravel 本地存储中的特定目录中删除文件

php - 如何在 PHP 中将数组声明为全局数组?

javascript - 如何在不使用 JSON 或任何东西的情况下使用纯 JavaScript/Ajax 调用此 HelloWorld Web 方法?

javascript - 使用 jQuery,如何根据页面高度限制广告单元的数量?

php - MySQL 半正矢公式中的语法错误

php - mysqli_fetch_assoc()期望参数/调用成员函数bind_param()错误。如何获取并修复实际的mysql错误?

php - cakephp、jquery、.ajax()、数据类型 : json

javascript - IE9 "Access is Denied"错误,访问IFrame时

javascript - 如何在 DIV 的垂直列表上执行 "nowrap"

javascript - 在 Array.find() 中使用异步函数