我有一个程序,我通过JavaScript随机选择一个单词,每当页面刷新或有人访问时,这个单词就会改变。
大体上,它看起来像这样(index.php文件的相关部分(:
<p> this is a <span class=“randomWord”></span> </p>
<script>:
let randomArray = [clarinet, chair, bubble, sofa, plant]
let randomNo = Math.floor(Math.random() * (randomArray.length -1) );
let randomW = document.querySelector(‘.randomWord’);
randomW.textContent = randomArray[randomNo];
</script>
我想做的是存储这个随机单词(来自randomW.textContent(。我想生成一个.txt文件并存储它(如果这是第一次访问(,或者将它连接到现有的.txt中,再连接到以前访问中的其他单词。
因此,例如,在5次访问之后,网站将显示";这是单簧管;txt文件是:椅子泡泡沙发单簧管
我有HTML5、CSS和JS的经验,但PHP对我来说仍然是一个巨大的未知数,所以不确定如何解决它。任何帮助或指导都将不胜感激!谢谢
最简单的方法是创建一个<form>
元素,并使action
属性指向一个PHP文件,在该文件中处理服务器逻辑。在本例中,我使用了POST方法。在表单中,将一个<input>
元素放入其value
属性中,该元素将从JavaScript接收随机单词。此输入将是发送到服务器的数据。
<form action="/save-random-word.php" method="POST">
<input type="hidden" id="randomW" name="randomW" value="" />
<button type="submit">Save random word</button>
</form>
在JavaScript中创建随机单词,并使用随机字符串设置输入元素的value
。现在,如果你要提交表格,随机单词就会被发送。
let randomArray = ['clarinet', 'chair', 'bubble', 'sofa', 'plant']
let randomNo = Math.floor(Math.random() * (randomArray.length -1) );
let randomW = document.querySelector('#randomW');
randomW.value = randomArray[randomNo];
现在,服务器有了一种接收数据的方法,这些数据是通过POST、GET或其他方法发送的。由于我使用了POST,我们需要检查全局$_POST
数组是否包含与输入的name
属性同名的键。在那里你可以找到数据。
如果.txt
文件还不存在,则创建一个新文件,或者读取该文件并将中间有空格的随机词添加到该文件的内容中,然后使用添加的内容再次存储该文件。
$randomW = isset( $_POST[ 'randomW' ] ) ? $_POST[ 'randomW' ] : '';
$file_name = './values.txt';
if ( ! is_file( $file_name ) ) {
file_put_contents( $file_name, $randomW );
} else {
$file_content = file_get_contents( $file_name );
$file_content .= ' ' . $randomW;
file_put_contents( $file_name, $file_contents );
}
die();
PHP部分
<?php
$fp = fopen('/path/to/words.txt', 'a'); //opens file in append mode
fwrite($fp, $_POST['word']."n");
fclose($fp);
?>
在Javascript方面,向这个PHP脚本发出POST请求,发送单词variable。