从php数组中获取随机值

时间:2014-06-23 18:40:33

标签: php jquery

我是PHP数组的新手,我已经阅读了不同的方法。我有一个工作的jQuery页面依赖于按下按钮。我想继续使用这些按钮。我想出了这段代码:

echo "
<script type='text/javascript'>
    $('.healthy_button').off('click').on('click', function(){

    " . $restChoice = array_rand($healthyRestaurants) . "

    console.log(\"restChoice =" . $healthyRestaurants[$restChoice] . "\");

    $('#result').html(\"Today, I suggest you eat at ---.\");
});
</script>
";

我不断收到$ restChoice未定义的错误,因为此行中的索引: console.log(\"restChoice =" . $healthyRestaurants[$restChoice] . "\");

正如您所看到的,我试图定义它。我错过了一些明显的东西吗?

3 个答案:

答案 0 :(得分:1)

假设已定义$healthyRestaurants,请在echo之外定义:

$restChoice = array_rand($healthyRestaurants);

echo "
<script type='text/javascript'>
    $('.healthy_button').off('click').on('click', function(){

    console.log(\"restChoice =" . $healthyRestaurants[$restChoice] . "\");

    $('#result').html(\"Today, I suggest you eat at ---.\");
});
</script>
";

答案 1 :(得分:1)

要在每次单击按钮时获取其他餐厅,请将PHP餐馆数组写入Javascript数组。然后在单击按钮时使用Javascript随机拉出餐馆。

<?php

$healthyRestaurants = array(
  "One",
  "Two",
  "Three",
  "Four",
  "Five"
);

?>

<button class="healthy_button">Restaurant</button>
<div id="result"></div>

<script>

var hR = <?php echo json_encode($healthyRestaurants); ?>;

$('.healthy_button').on('click', function(){
    var rand_rest = hR[Math.floor(Math.random()*hR.length)];
    $('#result').html("Today, I suggest you eat at " + rand_rest);
});

</script>

PHP代码无法执行Javascript代码,Javascript无法执行PHP代码。您可以共享信息,但如果他们有Facebook帐户,他们的关系状态将是“它很复杂”。

您可以将PHP“向下”硬编码到Javascript。 Javascript无法逆转这一点。要将值返回到PHP,您必须重新加载页面或使用XHR对象(AKA AJAX)。

为了最大限度地减少流量并为用户提供即时反馈,请使用PHP检索餐馆数组并将其写入Javascript变量。然后使用Javascript随机抽取餐馆并将其写入屏幕。

现在,如果您的餐馆列表数十万,并且下载到浏览器的费用太大,那么XHR对象会更有意义。

答案 2 :(得分:0)

使用heredoc减少了在文本中转义的需要,使其更具可读性......

我认为你的问题是你得到了JavaScript(+)和PHP(。)字符串连接混淆。

$restChoice = array_rand($healthyRestaurants);
echo <<<EOF
<script type='text/javascript'>
    $('.healthy_button').off('click').on('click', function(){

    {$restChoice}

    console.log("restChoice = {$healthyRestaurants[$restChoice]}");

    $('#result').html("Today, I suggest you eat at ---.");
});
</script>
EOF;
相关问题