例如我有这句话,“我喜欢弹钢琴。”它分为 4 个元素,将从数据库(myphpadmin)中取出。如何才能使其只有当我按下随机播放按钮时,它才会随机播放。
<body>
<?php
// Connect to database server
mysql_connect("localhost", "root", "password") or die (mysql_error ());
// Select database
mysql_select_db("login") or die(mysql_error());
// Get data from the database depending on the value of the id in the URL
$strSQL = "SELECT * FROM sentences WHERE id
ORDER BY RAND() LIMIT 1;";
//create an array with numbers 1-4
$order = array(1,2,3,4);
//shuffle them in random order
shuffle($order);
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the data of the person
//Display all the array values from 0-3 (array index starts from 0)
echo "<dt>Sentence:</dt><dd>" . $row[$order[0]] . " " . $row[$order[1]] . " " .
$row[$order[2]] . " " . $row[$order[3]] ."</dd>";
}
// Close the database connection
mysql_close();
?>
<button onClick="Shuffle()">Scramble</button>
</body>
最佳答案
您基本上需要使用 jQuery 来执行此操作.
利用jQuery.get()
对单独的 php 脚本运行 ajax 请求。
基本上你会有一个 php 脚本,你的代码设置如下:
我们称之为sentence.php
。
<?php
// Connect to database server
mysql_connect("localhost", "root", "password") or die (mysql_error ());
// Select database
mysql_select_db("login") or die(mysql_error());
// Get data from the database depending on the value of the id in the URL
$strSQL = "SELECT * FROM sentences WHERE id
ORDER BY RAND() LIMIT 1;";
//create an array with numbers 1-4
$order = array(1,2,3,4);
//shuffle them in random order
shuffle($order);
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the data of the person
//Display all the array values from 0-3 (array index starts from 0)
echo "<dt>Sentence:</dt><dd>" . $row[$order[0]] . " " . $row[$order[1]] . " " .
$row[$order[2]] . " " . $row[$order[3]] ."</dd>";
}
// Close the database connection
mysql_close();
?>
现在您已经有了 html 文件,我们将其命名为 index.html
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<button id="showcontent">Scramble</button>
<div id="content"></div>
</body>
</html>
在您的 script.js
中,您将运行 jQuery。
$(document).ready(function() {
$(document).on('click', '#showcontent', function(event) {
event.preventDefault();
$.get("sentence.php", function(data) {
$("div#content").html(data);
});
});
});
关于javascript - onClick 来自数据库的随机播放按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23902067/