Ajax局部刷新 - 异步请求(读写数据库)
实际工作中我们常会用到Ajax异步加载数据库数据,比如我们会伪造(不提倡)一个数据来写数据库,并时时反馈到页面中,之前就写过一个减肥页面的局部刷新。基本要求:1、定时写入数据库,成功减肥人数累加;2、随时读取数据展示到前台页面。
基本代码如下:
前台展示页:index.php
<script type="text/javascript" src="./js/jquery.js"></script>
<script type="text/javascript" src="./js/fun.js"></script>
<h2>Ajax异步请求(读写数据库)</h2>
人数(<span id="count" >loading ...</span>)
js代码 fun.js
function ajaxFresh(){
$.ajax({
type : 'POST',
url : 'ajaxReturn.php',
data : 'userid=12',
success : function(data){
//alert(data);
ajaxobj=eval("("+data+")");
document.getElementById("count").innerHTML=ajaxobj.count;
}
})
}
后台php处理程序 ajaxReturn.php
<?php
include "./mysql.php";
$table = "ice_ajax";
// 向数据库中写入数据
// 向数据库中写入数据
$step = mt_rand(1,10);
$sql = "UPDATE `ice_ajax` SET number=number+$step WHERE id=1";
mysql_query($sql);
$nums = getNum($table);
$info = array('count'=>$nums);
$userinfo = json_encode($info);
echo $userinfo;
mysql.php
<?php
$mysql_host = "localhost";
$mysql_host_s = "localhost";
$mysql_port = "3306";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "test";
$con = mysql_connect($mysql_host.':'.$mysql_port, $mysql_user, $mysql_password);
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_query("SET NAMES 'UTF8'");
mysql_select_db($mysql_database, $con);
//获取总人数
function getNum($table){
$sql = mysql_query("SELECT number FROM $table WHERE id='1'");
while ($row = mysql_fetch_array($sql)){
$total = $row[0];
}
return $total;
}
页面中依次执行多个异步请求获取数据
$('.ordernum').each(function(){
var a = $(this);
var kid = a.parents('tr').find('.kid').text();
$.ajax({
url : "{:U('Admin/getKfOrderNum')}",
data: {kid:kid},
type:'POST',
success:function(data){
a.html(data);
}
})
})