javascript - 从纯文本文件数据库中获取随机行

标签 javascript php html 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。这可能吗?

最佳答案

假设可以通过 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/

相关文章:

javascript - 使用javascript隐藏特定UL中的href元素

javascript - 如何使用 playwright 等待请求并验证响应?

javascript - Angular ui网格在列中显示数组

php - 使用 native PHP 功能是否比在 PHP 循环中做同样的事情更快?为什么?

php - SimpleTest:如何断言抛出 PHP 错误?

html - 页脚宽度问题

html - 为什么我不能滚动页面以查看我的 html 页面中 View 之外的内容?

javascript - jquery 复选框获取文本输入值

javascript - @font-face 更改 Leaflet.js 弹出行为

PHP/MySQL 使用速度单位对数字进行排序