好的,我有这个网站,它只是一个单页网站,中间有一些文字。我现在如何设置它是从我的数据库中抓取随机文本,表中只有一个字段。我将其反映为<p>
元素。一切都工作正常,除了现在我不想每次刷新页面以获得新文本。我希望能够单击按钮并更改文本而不刷新页面。
这是html非常简单:
<p>
<?php echo $story; ?>
</p>
这是PHP:
$mysql_host = "localhost";
$mysql_db = "scary";
$mysql_user = "root";
$mysql_pass = "";
$link = mysqli_connect($mysql_host, $mysql_user, $mysql_pass, $mysql_db) or die("Some error occurred during connection " . mysqli_error($link));
$result = mysqli_query($link, "SELECT * FROM `stories`");
$total_records = mysqli_num_rows($result);
$random_number = rand(0, $total_records - 1);
mysqli_data_seek($result, $random_number);
$array = mysqli_fetch_array($result);
$story = $array['Story'];
mysqli_free_result($result);
mysqli_close($link);
?>
我希望能够点击按钮并在没有页面刷新的情况下将正在回显的内容更改为<p>
。我怎么能做到这一点?
答案 0 :(得分:1)
你可以用jQuery做到这一点。在这个例子中我们有2个文件:index.html和random.php。
index.html来源
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#button").click(function(){
$("p").load("random.php",function(responseTxt,statusTxt,xhr){
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});
$("#button").click(); //loads random.php once at page load
});
</script>
<p></p>
<button id="button">Click Me</button>
random.php来源
<?
$mysql_host = "localhost";
$mysql_db = "scary";
$mysql_user = "root";
$mysql_pass = "";
$link = mysqli_connect($mysql_host, $mysql_user, $mysql_pass, $mysql_db) or die("Some error occurred during connection " . mysqli_error($link));
$result = mysqli_query($link, "SELECT * FROM `stories`");
$total_records = mysqli_num_rows($result);
$random_number = rand(0, $total_records - 1);
mysqli_data_seek($result, $random_number);
$array = mysqli_fetch_array($result);
$story = $array['Story'];
mysqli_free_result($result);
mysqli_close($link);
echo $story;
?>
请注意,这两个文件必须位于同一目录/路径中。顺便说一句,如果你想从mysql中随机获取一行,你可以使用这个命令而不是计算所有行而不是使用rand()等..:
SELECT * FROM `stories` ORDER BY RAND() LIMIT 1