gpt4 book ai didi

javascript - PHP 中的随机单词生成卡在同一个单词上

转载 作者:行者123 更新时间:2023-12-03 06:11:23 24 4
gpt4 key购买 nike

大家好,我是 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>

关于javascript - PHP 中的随机单词生成卡在同一个单词上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39299688/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com