随机单词生成卡在同一个单词在PHP


Random word generating stuck on the same word in PHP

嘿,伙计们,我是PHP新手,我想做一个页面,从文本文件中获得一个随机单词,下面是代码:

<?php
$chosen="Word";
function get(){
    $lines= file ("words.txt");
    $words=count($lines);
    $chosen=$lines[rand(0 ,$words - 1)];
    return $chosen;
}
?>

然后我从JS调用它:

word = <?php echo json_encode(get()); ?>;
document.getElementById("button").innerHTML = word

我得到的问题是函数第一次返回一个随机单词,但之后它是完全相同的单词一遍又一遍。

如果PHP能够生成你的JS代码,并且你不希望用AJAX弄得一团糟,那么试试这个:

index . php

<script>
// Get PHP to create a JS array
var all_words = <?php echo json_encode(file("words.txt")); ?>;
// Create a JS function to fetch a random word
function get_word(){
    // Don't go out of bounds and return a word
    return all_words[Math.floor((Math.random() * (all_words.length - 1)) + 1)];
}
// Call the function and enjoy :)
document.getElementById("button").innerHTML = get_word();
</script>