【问题标题】:Take line from .txt file and display in html page从 .txt 文件中取行并显示在 html 页面中
【发布时间】:2021-12-26 06:56:55
【问题描述】:

我想为我的女朋友做一个小项目,我的想法是有一个 HTML 页面,上面写着“我爱”。按下按钮后,网站会在文本下方显示我制作的文本文档中的随机行,其中包含我喜欢她的所有内容。例子: What I managed

所以我设法制作了一个只有“我爱”的页面,并在单击按钮时在其下方添加文本。但我希望它能够从 .txt 文件中随机抽取一行,其中每一行都是它会随机选择并显示在 html 上的一行文本。 谢谢

【问题讨论】:

  • 您不能从客户端加载服务器上的文件,因为这在安全性方面是一个巨大的禁忌。想象一下。您需要一些后端(服务器端)语言,例如 PHP。

标签: javascript html css txt


【解决方案1】:

您无法从客户端加载服务器上的文件,因为这在安全性方面是一个巨大的禁忌。想象一下。您需要一些后端(服务器端)语言,例如 PHP。

这是最基本的 PHP 代码(带有 cmets ),可以满足您的需求:

<?php
// you put your filename here ( obviously )
$fileName = "girl.txt";

// opening and reading file
$fileH = fopen( $fileName, "r") or die("Unable to open file!");
$fileCont = fread( $fileH,filesize( $fileName));
fclose($fileH);

// split text into lines
$lines = explode( "\r\n", $fileCont);
$numOfLines = count($lines);

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <!-- import math module -->
    <script src=https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.3.0/math.min.js></script>
</head>
<body>
    <!-- prints random choice to html code -->
    <h1>I Love</h1>
    <button>Click Me!</button>
    

    <script>
        // print php array into js
        <?php echo "lines = ['".join("', '", $lines)."'];\n"; ?>
        maxLineNum = <?php echo $numOfLines; ?>;

        // on button click you get random msg in h1
        document.querySelector("button").addEventListener( "click", ()=>{
            randNum = math.floor( math.random()*maxLineNum );
            document.querySelector("h1").textContent = "I love " + lines[randNum];
        } );

    </script>
</body>
</html>

【讨论】:

  • 您好,您发送的代码似乎对我没有任何作用,我使用 XAMPP 打开它并打开 php 文件没有问题,但是当我单击按钮时它没有从我的 .txt 文件中显示不同的行。它只是复制粘贴代码还是我必须采取任何其他步骤。 `
  • 你的 PHP 版本是多少?你给你的文件起什么名字?您的文件与php文件位于同一目录中吗?文件应该有多行,其中每一行是完成“我爱..”引用的单词。
  • 我的 PHP 版本是“PHP 7.3.29”,文件都位于同一个目录中(在本例中,在 htdocs 文件夹中,我用我的 php、css 和 txt 文件创建了一个文件夹),在 .txt 文件中有各种行,但当我单击按钮时它不显示任何行。名称是 getlines.txt,我已在 .php 中将其更改为该地址。
  • 您有任何错误吗?你检查过你的 JS 控制台吗?我的意思是,你并没有真正帮助我帮助你解决“它不起作用兄弟”。
  • 您好,我找到了只使用 php 的替代方案,但非常感谢您帮助我。非常感谢。
【解决方案2】:

我是 JavaScript 新手,但我会尝试将 sn-ps 存储在 JS 本身的数组中,而不是将它们放在单独的文本文件中,这样在使用之前需要对其进行访问和处理。

JS:

const niceSnippets = [
  ‘your smile’,
  ‘your sense of humour’, // repeat for as many snippets as you can think of
  ‘you’
];

const chooseSnippet = () => { niceSnippets[Math.floor(Math.random()*niceSnippets.length)]; }

const changeSnippet = () => { document.getElementById('snippetDisplay').innerText = chooseSnippet(); }

用 id 和 onclick 更新 HTML 中的相关元素:

<p id=“snippetDisplay”></p>
<button onclick=“changeSnippet()”>Click Me!</button>

【讨论】:

  • 他说来自.txt
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
  • 2018-05-09
  • 2014-02-18
  • 2017-11-09
  • 1970-01-01
  • 2013-09-03
  • 1970-01-01
相关资源
最近更新 更多