簡體   English   中英

隨機單詞生成卡在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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM