我有一个简单的PHP脚本,它从文本文件中读取特定的短语,并在网页上随机显示。为了显示另一个随机短语,目前必须刷新整个页面。我的问题是 - 有没有办法只更新包含短语的页面区域,每次单击按钮时显示一个新短语?目前,下面的PHP包含在使用CSS设置样式的h1标记中。然后我在其下面添加一条评论,告诉用户刷新页面以显示另一个随机短语。理想情况下,我希望将此注释更改为按钮,以便用户不必每次都刷新整个页面。
以下是用于显示随机短语的简单PHP:
$str = file_get_contents('words.txt'); //Take the contents from the file to the variable
$result = explode(',',$str); //Split it by ','
echo $result[array_rand($result)]; //Return a random entry from the array.
非常感谢任何帮助。
干杯,汤姆
答案 0 :(得分:1)
我能想到的两种方式:
答案 1 :(得分:1)
示例我以前开始学习PHP / AJX,摘自Using jQuery ...
创建一个php脚本来接收http请求并从数据库中获取数据
//--------------------------------------------------------------------------
// Example php script for fetching data from mysql database
//--------------------------------------------------------------------------
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "ajax01";
$tableName = "variables";
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
include 'DB.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName"); //query
$array = mysql_fetch_row($result); //fetch result
//--------------------------------------------------------------------------
// 3) echo result as json
//--------------------------------------------------------------------------
echo json_encode($array);
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
//recommend reading up on jquery selectors they are awesome
// http://api.jquery.com/category/selectors/
}
});
});
</script>
</body>
答案 2 :(得分:0)
使用jQuery这很容易:
HTML:
<div id="random"></div>
<input type="button" id="update" />
的javascript:
<script>
$("#update").on("click", function() {
$.ajax({
url: "/randomwords.php",
success: function(data) { $("#random").html(data); }
});
});
</script>
randomwords.php
是您上面的片段而没有任何其他内容。