Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
Tome la línea del archivo .txt y muéstrela en la página html

Quiero hacer un pequeño proyecto para mi novia y lo que tenía en mente era tener una página HTML que diga "Me encanta". Al presionar un botón, el sitio web mostraría debajo del texto una línea aleatoria de un documento de texto que hice con todas las cosas que amo de ella. Ejemplo: Lo que logré

Entonces logré hacer una página con solo "ME ENCANTA" y agregar el texto debajo cuando hago clic en el botón. Pero me gustaría poder tomar una línea aleatoria de un archivo .txt donde cada línea sería una línea de texto que elegiría aleatoriamente y mostraría en el html. Gracias

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

No puede cargar desde archivos en el servidor desde el lado del cliente porque sería un gran no-no cuando se trata de seguridad. Solo imagina eso. Necesita algún lenguaje de back-end (lado del servidor) como PHP.

Aquí está el código PHP más básico (con comentarios) que hace lo que quieres:

 <?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>
about 4 years ago · Juan Pablo Isaza Report

0

Soy nuevo en JavaScript, pero intentaría almacenar los fragmentos en una matriz en el propio JS en lugar de colocarlos en un archivo de texto separado al que luego se debe acceder y procesar antes de poder usarlo.

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(); }

con los elementos relevantes en el HTML actualizado con id y onclick:

 <p id=“snippetDisplay”></p> <button onclick=“changeSnippet()”>Click Me!</button>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!