我感兴趣以下 php 脚本是否可以用 Javascript(或 HTML5)编写?基本上,这只是一个简单的文件,读取 .txt 并显示其中的随机行:
<?php
$text = file_get_contents('flatFileDB.txt');
$textArray = explode("\n", $text);
$randArrayIndexNum = array_rand($textArray);
$randPhrase = $textArray[$randArrayIndexNum];
?>
<html>
<body>
<h2><?php echo $randPhrase; ?></h2>
</body>
</html>
“flatFileDB.txt”示例:
Line 1
Line 2
Line 3
Line 4
Line 5
...
...
etc
示例取自此处:http://www.developphp.com/view.php?tid=1213 ,我想做同样的事情,但没有服务器端 php。这可能吗?
最佳答案
假设可以通过 http://www.example.com/flatFileDB.txt
访问平面文件数据库,并且您的 HTML 文件的 div 的 id 值为 random-短语
:
var request = new XMLHttpRequest();
request.onload = function() {
// get the file contents
var fileContent = this.responseText;
// split into lines
var fileContentLines = fileContent.split( '\n' );
// get a random index (line number)
var randomLineIndex = Math.floor( Math.random() * fileContentLines.length );
// extract the value
var randomLine = fileContentLines[ randomLineIndex ];
// add the random line in a div
document.getElementById( 'random-phrase' ).innerHTML = randomLine;
};
request.open( 'GET', 'http://www.example.com/flatFileDB.txt', true );
request.send();
看here有关 XMLHttpRequest
的文档,它允许您异步检索文件。
关于javascript - 从纯文本文件数据库中获取随机行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21558336/