HTML / JavaScript 中的随机句子生成器

Random Sentence generator in HTML / JavaScript

我正在寻找一个带有随机句子生成器的简单迷你网站。当访问者单击按钮时,网站会显示从短语数据库中提取的随机短语。

如果可能的话,第二个迷你网站允许用户为将要用于第一个迷你网站的数据库添加他们自己的短语。

我在手工编码方面还是个新手,但我正在努力

像这样:
第一个站点:First site
第二个站点:Second site

我不太了解数据库,但是使用 js 和一点 jQuery,您可以这样做:

1. 创建一个包含所有短语的数组:

var phrases = [
["Phrase 1"],
["Phrase 2"],
["Phrase 3"]
];

2. 创建一个随机化短语的函数(我使用 jQuery 获取显示短语的文本的 ID,但您可以使用 getElementById 如果你愿意的话):

var randPhraseNum = Math.floor(Math.random() * phrases.length);
$("#phraseText").text(phrases[randPhraseNum]);

3. 使用 push() 方法向数组中添加新短语:

phrases.push("New Phrase");

我知道这不是您想要的,但我希望它能有所帮助。

使用 php 和 javascript 我创建了 2 个文件。

  • call.php - 从数据库中检索一个句子并打印其中一个(随机)
  • index.html - 一个带有按钮的页面,该按钮运行一个函数,该函数从 call.php
  • 中检索一个句子

call.php:

<?php
$db_host = "localhost"; //Host address (most likely localhost)
$db_name = "DATABASE_NAME"; //Name of Database
$db_user = "DATABASE_USERNAME"; //Name of database user
$db_pass = "DATABASE_PASSWORD"; //Password for database user
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

$stmt = $mysqli->prepare("SELECT sentence
                FROM `table_sentences`
                "); //gets all the values in the column "sentence" from the table `table_sentences`
$stmt->execute(); //Execute the query
$stmt->bind_result($sentence); //Bind the results into array
$array = array(); 
while ($stmt->fetch()){
    array_push($array,$sentence); //enter each sentence, in to the array ($array)
}
$stmt->close(); //Close the connection

$rand = array_rand($array, 1); //Random one value from the array

echo $rand[0]; //Echo the value

index.html:

<html>
<head>
<script>
function getSentence() { //defines a function named getSentence
    var xhr = new XMLHttpRequest(); //creating a new request
    xhr.open("get", "call.php", true); //setting the file to get the data from
    xhr.onload = function(){
        var response = xhr.responseText; //Save the sentence into a var
        document.getElementById("text").innerHTML = response; //Set where the sentence should display
    }
    xhr.setRequestHeader('Cache-Control', 'no-cache'); //Prevent caching
    xhr.send(null); //Submit the request
}
</script>
</head>
<body>
<p id="text"></p>
<button onClick="getSentence()">Get Sentence</button>
</body>
</html>