随机单词生成卡在同一个单词在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>
相关文章:
- 使用php或javascript从facebook相册URL中删除多余的部分
- 将PHP变量传递给jQuery时遇到问题
- 通过javascript重定向html传递php变量
- 将数组从PHP传递到Javascript
- JavaScript 数组到同一个 php 文件上的 php 脚本
- 如何在同一个.js文件中编写ajax,php和js并从数据库中检索数据
- 如何防止php中两个独立的ajax调用修改同一个数据库
- 在同一个html中使用javascript和php
- 向同一个php文件发送AJAX调用
- 从javascript发送一个字符串到php(在同一个文件中)
- 如何在同一个按钮上运行PHP动作和javascript代码
- 如果我们希望PHP中的数据保存在同一个文件中,我们能做些什么来代替javascript中的ajax调用呢?
- 随机单词生成卡在同一个单词在PHP
- 两个电子邮件在同一个文件php
- 使用javascript switch语句在同一个文件中调用php函数
- 在同一个域上使用javascript读取php文件
- 只有当jQuery在同一个PHP文件中时,jShowOff才能在WP中工作
- 在同一个(.js)文件和另一个PHP文件中调用Jquery函数
- I'm试图在同一个文件(Google Maps API)中将Javascript变量传递给PHP
- 同一个函数在php和javascript上的两个不同输出