从平面文本文件数据库中获取随机行

时间:2014-02-04 16:44:55

标签: javascript php html5 random flat-file

我感兴趣的是以下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。它甚至可能吗?

1 个答案:

答案 0 :(得分:2)

假设可以在http://www.example.com/flatFileDB.txt访问平面文件数据库,并且您的HTML文件包含id值为random-phrase的div:

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上的文档,该文档允许您异步检索文件。