我有一个简单的 PHP 脚本,它从文本文件中读取特定短语并在网页上随机显示一个。为了显示另一个随机短语,目前必须刷新整个页面。我的问题是 - 有没有办法只更新包含该短语的页面区域,每次单击按钮时显示一个新短语?目前,下面的 PHP 包含在 h1 标签中,该标签已使用 CSS 进行样式设置。然后,我在其下方添加一条注释,告诉用户刷新页面以显示另一个随机短语。理想情况下,我希望将此评论更改为按钮,以便用户不必每次都刷新整个页面。
这是用于显示随机短语的简单 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.
任何帮助将不胜感激。
干杯,汤姆
最佳答案
我曾经开始学习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);
客户端示例
输出:
该元素将被 jquery 访问并替换该文本<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>
关于php - 更新网页的特定区域而不重新加载整个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10951591/