【问题标题】:Fetching Random Line From Flat Text File Database从平面文本文件数据库中获取随机行
【发布时间】:2014-02-28 18:25:21
【问题描述】:

我对以下 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。有没有可能?

【问题讨论】:

  • 有可能吗?是的
  • 好的,既然我们已经确定这是可能的,那么让我们来寻找解决方案。
  • Ajax 调用或文件 api,获取文本,在新行上拆分字符串,生成随机数,从数组中选择索引。玩得开心编码。

标签: javascript php html random flat-file


【解决方案1】:

假设可以在http://www.example.com/flatFileDB.txt 访问平面文件DB,并且您的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 上的文档,该文档允许您异步检索文件。

【讨论】:

  • 对不起,我是 JS 的菜鸟 - 你能给我替换 ?
  • 你不能在 JS 中“回显”。您需要有一个可以更改其值的 HTML 元素(例如 div / span)
  • @user3271739 我已经为你添加了一个解决方案。
  • 所以我应该把所有这些都放到 中,然后将
    放到 的某个地方?
  • 是的,在 &lt;script&gt;&lt;/script&gt; 标签内。并确保您已将数据库文件上传到某处。
猜你喜欢
  • 2015-01-06
  • 1970-01-01
  • 2015-11-26
  • 2017-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多