这是本人在学习ajax过程所做的笔记,通过本笔记的学习,可以完成ajax的快速入门。本笔记前端分别使用原生态的javascript语言和jQuery语言,服务器端使用PHP语言。
//创建ajax引擎
function getXMLHttpRequest() {
var xmlhttp;
try {
//Firefox,Opera 8.0+, Safari
xmlhttp = new XMLHttpRequest();
}catch (e) {
//Internet Explorer
try {
xmlhttp = new ActiveXObject(“Msxml12.XMLHTTP”);
}catch (e) {
try {
xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”);
}catch (e) {
alert(“您的浏览器不支持AJAX!”);
return false;
}
}
}
return xmlhttp;
}
基本格式
|
例子
|
“{属性名:属性值,属性名:属性值……}”
|
<script type=”text/javascript”>
var dog = {“name”:”小明”,”age”:”18”,”键”:”值”……}
alert(dog.name);
alert(dog.age);
</script>
|
[
{名称1:值1,名称2:值2,……}
{名称1:值1,名称2:值2,……}
|
<script type=”text/javascript”>
var dog = [
{“name”:”小名”,”age”:”3″},
{“name”:”小花”,”age”:”4″}
for(var i = 0; i < dog.length; i++) {
alert(dog.name);
alert(dog.age);
}
</script>
|
扩展格式
|
<script language=”JavaScript”>
var people ={
“programmers”:
[
{“firstName”: “Brett”, “email”: “brett@newInstance.com” },
{“firstName”: “Jason”, “email”: “jason@servlets.com” }
};
window.alert(people.programmers[0].firstName);
window.alert(people.programmers[1].email);
</script>
|
扩展格式
|
<script language=”JavaScript”>
var people ={
“programmers”: [
{ “firstName”: “Brett”, “email”: “brett@newInstance.com” },
{ “firstName”: “Jason”, “email”: “jason@servlets.com” },
{ “firstName”: “Elliotte”, “lastName”:”Harold”, “email”: “elharo@macfaq.com” }
],
“authors”: [
{ “firstName”: “Isaac”, “genre”: “science fiction” },
{ “firstName”: “Tad”, “genre”: “fantasy” },
{ “firstName”: “Frank”, “genre”: “christian fiction” }
],
“musicians”: [
{ “firstName”: “Eric”, “instrument”: “guitar” },
{ “firstName”: “Sergei”, “instrument”: “piano” }
]};
window.alert(people.programmers[1].firstName);
window.alert(people.musicians[1].instrument);
</script>
|
扩展格式
|
<script language=”JavaScript”>
var people ={
“username”:”mary”,
“age”:”20″,
“info”:{“tel”:”1234566″,”celltelphone”:788666},
“address”:[
{“city”:”beijing”,”code”:”1000022″},
{“city”:”shanghai”,”code”:”2210444″}
};
window.alert(people.username);
window.alert(people.info.tel);
window.alert(people.address[0].city);
</script>
|
13、三种格式的对比
文本格式
|
1、数据量小,但不需要和其他程序通信时较为适用
|
XML格式
|
1、格式通用能够和其他应用程序通信
2、当远程应用程序未知的时候是首选
|
JSON格式
|
1、原生态数据,描述能力强,数据结构简单
2、格式要求严格
3、元素的数据类型可以是int,string,float,boolean,array,object等基本数据格式
4、eval函数有一定的风险
5、如果无特殊需求推荐使用
|
14、如果我们的代码比较复杂,可以使用file_put_contents函数,将数据输出到日志文件进行查看,调试
<html>
<head>
<title>用户注册</title>
<script type=”text/javascript”>
var xmlhttp = null;
function (id) {
return document.getElementById(id);
}//创建ajax引擎
function getXMLHttpRequest() {
var xmlhttp;
try {
//Firefox,Opera 8.0+, Safari
xmlhttp = new XMLHttpRequest();
//alert(“Firefox,Opera 8.0+, Safari”);
}catch (e) {
//Internet Explorer
try {
//Internet Explorer 6.0+
xmlhttp = new ActiveXObject(“Msxml12.XMLHTTP”);
//alert(“Internet Explorer 6.0+”);
}catch (e) {
try {
//Internet Explorer 5.5+
xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”);
//alert(“Internet Explorer 5.5+”);
}catch (e) {
alert(“您的浏览器不支持AJAX!”);
return false;
}
}
}
return xmlhttp;
}//验证用户名是否存在
function checkName() {
xmlhttp = getXMLHttpRequest();//怎么判断创建是否成功
(“username”).value;
if (xmlhttp) {
//通过xmlhttprequest对象,发送请求到服务器
//第一个参数表示请求的方式get或者post
//第二个参数指定URL,其本质仍然是HTTP请求
//第三个参数指定是否采用异步机制
/*
//以get方式发送
var url = “/ajax/register/register.php?datetime=”+new Date()+”&username=”+
xmlhttp.open(“get”, url, true);//打开请求
//指定回调函数,指定的函数名一定不要带括号
xmlhttp.onreadystatechange = chuli;
//发送请求
xmlhttp.send();
*/
//以post方式发送
var url = “/ajax/register/register.php”;
var data = “username=”+(“username”).value;
xmlhttp.open(“post”, url, true);//打开请求
//下面这句话是post方式发送时必须要
xmlhttp.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);
//指定回调函数,指定的函数名一定不要带括号
xmlhttp.onreadystatechange = chuli;
//发送请求
xmlhttp.send(data);
}
}//处理函数
(“myres”).value = xmlhttp.responseText;
function chuli() {
//alert(“处理函数被调用”+xmlhttp.readyState);
//取出从服务器返回的数据
if (xmlhttp.readyState == 4) {
//取出值,根据返回信息的格式而定
//window.alert(“服务器返回值为:”+xmlhttp.responseText);
}
}
</script>
</head>
<body>
<form action=”#” method=”post”>
用户姓名:<input type=”text” name=”username1″ id=”username” onkeyup=”checkName();” />
<input type=”button” onclick=”checkName();” value=”验证用户名” />
<input style=”border-width: 0;color: red” type=”text” id=”myres” /><br>
用户密码:<input type=”password” name=”password”/><br>
电子邮箱:<input type=”text” name=”email”/><br>
<input type=”submit” value=”用户注册” />
</form>
<br>
<form action=”#” method=”post”>
用户姓名:<input type=”text” name=”username” />
<input style=”border-width: 0;color: red” type=”text” id=”myres” /><br>
用户密码:<input type=”password” name=”password”/><br>
电子邮箱:<input type=”text” name=”email”/><br>
<input type=”submit” value=”用户注册” />
</form>
</body>
</html>
<?php
//设置返回的格式
header(“Content-Type:text/html;charset=utf-8”);
//设置禁用缓存
header(“Cache-Control:no-cache”);
//接受数据
//username =_GET[‘username’];
username =_POST[‘username’];
if ($username == “wuhaohua”) {
echo “用户名不可用”;
}else {
echo “用户名可用”;
}
?>
<script type=”text/javascript”>
//处理函数
function chuli() {
//alert(“处理函数被调用”+xmlhttp.readyState);
//取出从服务器返回的数据
if (xmlhttp.readyState == 4) {
//取出值,根据返回信息的格式而定
//取出XML文本格式
//获取msg节点
var msg = xmlhttp.responseXML.getElementsByTagName(“msg”);
//取出msg节点的值
//msg[0]表示取出第一个msg节点
//msg[0]msg[0].childNodes[0]表示取出msg节点的第一个子节点
var msg_val = msg[0].childNodes[0].nodeValue;
$(“myres”).value = msg_val;
}
}
</script>
<?php
//设置返回的格式
header(“Content-Type:text/xml;charset=utf-8”);
//设置禁用缓存
header(“Cache-Control:no-cache”);
//接受数据
username =_POST[‘username’];//返回xml格式数据
info = “”;
if (username == “wuhaohua”) {
info = “<res><msg>用户名不可用,对不起</msg></res>”;
}else {info = “<res><msg>用户名可用,恭喜</msg></res>”;
}
echo $info;
?>
//处理函数
function chuli() {
//alert(“处理函数被调用”+xmlhttp.readyState);
//取出从服务器返回的数据
if (xmlhttp.readyState == 4) {
//取出值,根据返回信息的格式而定
//取出json文本格式
var msg = xmlhttp.responseText;
//将字符串转换成json对象
var json_obj = eval(“(“+msg+”)”);
//取出json对象的属性
$(“myres”).value = json_obj.res;
}
}
<?php
//设置返回的格式
header(“Content-Type:text/html;charset=utf-8”);
//设置禁用缓存
header(“Cache-Control:no-cache”);
//接受数据
username =_POST[‘username’];//返回xml格式数据
info = “”;
if (username == “wuhaohua”) {
info = ‘{“res”:”该用户名不可用”}’;//json格式的字符串
}else {info = ‘{“res”:”该用户名可用”}’;//json格式的字符串
}
echo $info;
?>
<html>
<head>
<title>省市联动</title>
<meta content=”text/html; charset=UTF-8″ http-equiv=”content-type” />
<script type=”text/javascript”>
var xmlhttp;function (id) {
return document.getElementById(id);
}//创建ajax引擎
function getXMLHttpRequest() {
var xmlhttp;
try {
//Firefox,Opera 8.0+, Safari
xmlhttp = new XMLHttpRequest();
//alert(“Firefox,Opera 8.0+, Safari”);
}catch (e) {
//Internet Explorer
try {
//Internet Explorer 6.0+
xmlhttp = new ActiveXObject(“Msxml12.XMLHTTP”);
//alert(“Internet Explorer 6.0+”);
}catch (e) {
try {
//Internet Explorer 5.5+
xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”);
//alert(“Internet Explorer 5.5+”);
}catch (e) {
alert(“您的浏览器不支持AJAX!”);
return false;
}
}
}
return xmlhttp;
}function getCity() {
var url = “/ajax/provinces/provinces.php”;
var data = “province=”+(“province”).value;
xmlhttp = getXMLHttpRequest(); // 获取对象
xmlhttp.open(“POST”, url, true);// 打开请求
xmlhttp.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);//设置报文头部
xmlhttp.onreadystatechange = chuliCity;// 设置回调函数
xmlhttp.send(data); //发送数据
}function chuliCity() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//服务器处理完成并且成功
//删除select中所有的项
(‘city’).options.length = 0;
//添加默认项
//var defaultoption = document.createElement(“option”);
//defaultoption.value = “”;
//defaultoption.innerText = “—市—“;
//(‘city’).appendChild(defaultoption);
var cities = xmlhttp.responseXML.getElementsByTagName(“city”);
for (var i = 0; i < cities.length; i++) {
var city = cities[i].childNodes[0].nodeValue;
//创建option结点
var myoption = document.createElement(“option”);
myoption.value = city;
myoption.innerText = city;
//添加option结点
$(‘city’).appendChild(myoption);
}
}
}</script>
</head>
<body>
<select id=”province” onchange=”getCity();”>
<option value=””>—省—</option>
<option value=”sichuan”>四川</option>
<option value=”gansu”>甘肃</option>
</select>
<select id=”city” onchange=”getCountry();”>
<option value=””>—市—</option>
</select>
<select id=”country”>
<option value=””>—县—</option>
</select>
</body>
</html>
<?php
//设置返回的格式
header(“Content-Type:text/xml;charset=utf-8”);
//设置禁用缓存
header(“Cache-Control:no-cache”);//接收客户端数据
province =_POST[‘province’];
info=””;
if (province == “sichuan”) {
info=”<province><city>成都</city><city>广元</city><city>绵阳</city></province>”;
}elseif (province == “gansu”) {
info=”<province><city>兰州</city><city>武威</city><city>酒泉</city></province>”;
}else {info=”<province><city>—市—</city></province>”;
}echo $info;
?>
<html>
<head>
<title>省市联动</title>
<meta content=”text/html; charset=UTF-8″ http-equiv=”content-type” />
<script type=”text/javascript” src=”../js/jquery-1.8.3.min.js”></script>
<script type=”text/javascript”>
(function (){(‘#province’).change(function (){
//id为province的标签的onchange事件被触发
(‘#city’).load(“/ajax/provinces/provinces.php”, {province:(‘#province option:selected’).val()}, function(responseText, textStatus, XMLHttpRequest) {
//发送ajax请求并接收回传值
if (textStatus == “success”) {
//请求成功
var msg_obj = eval(“(“+responseText+”)”);
for (var i = 0; i < msg_obj.length; i++) {
//alert(“<option value='”+msg_obj[i].city_value+”‘>”+msg_obj[i].city_name+”</option>”);
var myoption =(“<option value=\””+msg_obj[i].city_value+”\”>”+msg_obj[i].city_name+”</option>”);
(“#city”).append(myoption);
}
}
});
});
});
</script>
</head>
<body>
<select id=”province”>
<option value=””>—省—</option>
<option value=”sichuan”>四川</option>
<option value=”gansu”>甘肃</option>
</select>
<select id=”city” onchange=”getCountry();”>
<option value=””>—市—</option>
</select>
<select id=”country”>
<option value=””>—县—</option>
</select>
</body>
</html>
<?php
//设置返回的格式
header(“Content-Type:text/html;charset=utf-8”);
//设置禁用缓存
header(“Cache-Control:no-cache”);//接收客户端数据
province =_POST[‘province’];
// echo province;info=””;
if (province == “sichuan”) {info='[{“city_value”:”chengdu”,”city_name”:”成都”},{“city_value”:”guangyuan”,”city_name”:”广元”},{“city_value”:”mianyang”,”city_name”:”绵阳”}]’;
}elseif (province == “gansu”) {info='[{“city_value”:”lanzhou”,”city_name”:”兰州”},{“city_value”:”wuwei”,”city_name”:”武威”},{“city_value”:”jiuquan”,”city_name”:”酒泉”}]’;
}else {
info='[{“city_value”:””,”city_name”:”—市—“}]’;
}echoinfo;
?>
<html>
<head>
<title>省市联动</title>
<meta content=”text/html; charset=UTF-8″ http-equiv=”content-type” />
<script type=”text/javascript” src=”../js/jquery-1.8.3.min.js”></script>
<script type=”text/javascript”>
(function (){(‘#province’).change(function (){
//id为province的标签的onchange事件被触发
.get(“/ajax/provinces/provinces.php”, {province:(“#province option:selected”).val()}, function (data, textStatus) {
(“#city”).empty();(data).find(“city”).each(function() {
var myoption =(“<option value\””+(this).attr(“name”)+”\”>”+(this).text()+”</option>”);
(“#city”).append(myoption);
});
});
});
});
</script>
</head>
<body>
<select id=”province”>
<option value=””>—省—</option>
<option value=”sichuan”>四川</option>
<option value=”gansu”>甘肃</option>
</select>
<select id=”city” onchange=”getCountry();”>
<option value=””>—市—</option>
</select>
<select id=”country”>
<option value=””>—县—</option>
</select>
</body>
</html>
<?php
//设置返回的格式
header(“Content-Type:text/xml;charset=utf-8”);
//设置禁用缓存
header(“Cache-Control:no-cache”);//接收客户端数据
province =_GET[‘province’];
// echo province;info=””;
if (province == “sichuan”) {
//info='[{“city_value”:”chengdu”,”city_name”:”成都”},{“city_value”:”guangyuan”,”city_name”:”广元”},{“city_value”:”mianyang”,”city_name”:”绵阳”}]’;
info = “<province><city name=’chengdu’>成都</city><city name=’guangyuan’>广元</city><city name=’mianyang’>绵阳</city></province>”;
}elseif (province == “gansu”) {
//info='[{“city_value”:”lanzhou”,”city_name”:”兰州”},{“city_value”:”wuwei”,”city_name”:”武威”},{“city_value”:”jiuquan”,”city_name”:”酒泉”}]’;info = “<province><city name=’lanzhou’>兰州</city><city name=’wuwei’>武威</city><city name=’jiuquan’>酒泉</city></province>”;
}else {
//info='[{“city_value”:””,”city_name”:”—市—“}]’;info = “<province><city name=”>—市—</city></province>”;
}echo $info;
?>
<html>
<head>
<title>省市联动</title>
<meta content=”text/html; charset=UTF-8″ http-equiv=”content-type” />
<script type=”text/javascript” src=”../js/jquery-1.8.3.min.js”></script>
<script type=”text/javascript”>
(function (){(‘#province’).change(function (){
//id为province的标签的onchange事件被触发
.post(“/ajax/provinces/provinces.php”, {province:(“#province option:selected”).val()}, function (data, textStatus) {
(“#city”).empty();
for (var i = 0; imyoption = (“<option value='”+data[i].city_value+”‘>”+data[i].city_name+”</option>”);(“#city”).append($myoption);
}
}, “json”);
});
});
</script>
</head>
<body>
<select id=”province”>
<option value=””>—省—</option>
<option value=”sichuan”>四川</option>
<option value=”gansu”>甘肃</option>
</select>
<select id=”city” onchange=”getCountry();”>
<option value=””>—市—</option>
</select>
<select id=”country”>
<option value=””>—县—</option>
</select>
</body>
</html>
<?php
//设置返回的格式
header ( “Content-Type:text/html;charset=utf-8” );
//设置禁用缓存
header ( “Cache-Control:no-cache” );//接收客户端数据
province =_REQUEST [‘province’];
// echo province;info = “”;
if (province == “sichuan”) {info='[{“city_value”:”chengdu”,”city_name”:”成都”},{“city_value”:”guangyuan”,”city_name”:”广元”},{“city_value”:”mianyang”,”city_name”:”绵阳”}]’;
// info = “<province><city name=’chengdu’>成都</city><city name=’guangyuan’>广元</city><city name=’mianyang’>绵阳</city></province>”;
} elseif (province == “gansu”) {
info='[{“city_value”:”lanzhou”,”city_name”:”兰州”},{“city_value”:”wuwei”,”city_name”:”武威”},{“city_value”:”jiuquan”,”city_name”:”酒泉”}]’;
//info = “<province><city name=’lanzhou’>兰州</city><city name=’wuwei’>武威</city><city name=’jiuquan’>酒泉</city></province>”;
} else {
info='[{“city_value”:””,”city_name”:”—市—“}]’;
//info = “<province><city name=”>—市—</city></province>”;
}echo $info;
?>
<!DOCTYPE unspecified PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<title>天气预报查询</title>
<meta content=”text/html; charset=utf-8″>
<script type=”text/javascript” src=”../js/jquery-1.8.3.min.js”></script>
<script type=”text/javascript” src=”weather_forecast.js”></script>
<style type=”text/css”>
table.weather {
table-layout: fixed;
text-align: center;
}table.index {
width: 580px;
}body {
font-family: 仿宋;
}select {
width: 80px;
}
</style>
</head>
<body>
<center>
<select id=”province”>
<option value=””>—省—</option>
<?php
//打开数据库
connect = mysql_connect ( “localhost”, “root”, “” );
mysql_select_db ( “weather_forecast” );
mysql_query ( “set names utf8” );
//查询省份数据sql = “select * from `province`”;
result = mysql_query (sql );
if (result && mysql_num_rows (result ) > 0) {
//如果数据不为空,则逐条解析并加入下拉列表
while ( arr = mysql_fetch_array (result ) ) {
echo “<option value='” . arr [“id”] . “‘>” .arr [“name”] . “</option>”;
}
}
mysql_close ( $connect );
?>
</select> <select id=”city”>
<option value=””>—市—</option>
</select>
<button id=”commit”>查询</button>
<hr />
<div id=”weather”></div>
</center>
</body>
</html>
<?php
//设置返回的格式
header ( “Content-Type:text/html;charset=utf-8” );
//设置禁用缓存
header ( “Cache-Control:no-cache” );//接收省份数据
province_id =_POST [‘province’];//打开数据库
connect = mysql_connect ( “localhost”, “root”, “” );
mysql_select_db ( “weather_forecast” );
mysql_query ( “set names utf8” );
//查询数据sql = “select `name`, `city_number` from `city` where `province_id` = ‘” . province_id . “‘”;result = mysql_query ( sql );info = “”;
if (mysql_num_rows ( result )>0) {info = “[“;
while ( array = mysql_fetch_array (result ) ) {
info =info.'{“name”:”‘.array[“name”].'”,”city_number”:”‘.array[“city_number”].'”},’;
}
info = substr(info, 0, strlen(info)-1);info .= “]”;
}
echo $info;
?>
<?php
//接受城市代码
city_number =_POST[‘city_number’];//初始化
ch = curl_init();curl_setopt(ch, CURLOPT_URL, “http://m.weather.com.cn/data/”.city_number.”.html”);
curl_setopt(ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(ch, CURLOPT_HEADER, 0);
// 3. 执行并获取HTML文档内容output = curl_exec(ch);
// 4. 释放curl句柄
curl_close(ch);echo $output;
?>
$(function() {
$(“#province”).change(
function() {
$.ajax({
url : “/ajax/weather_forecast/city.php”,
type : “POST”,
data : {
province : $(“#province option:selected”).val()
},
dataType : “json”,
success : function(data) {
if (data == null || data == “”) {
$(“#city”).empty();
$myoption = $(“<option value=”>—市—</option>”);
$(“#city”).append($myoption);
return;
}
$(“#city”).empty();
for ( var i = 0; i < data.length; i++) {
$myoption = $(“<option value='”
+ data[i].city_number + “‘>” + data[i].name
+ “</option>”);
$(“#city”).append($myoption);
}
}
});
});$(“button”).click(
function() {
if ($(“#city”).val() == null || $(“#city”).val() == “”) {
window.alert(“请选择正确省份和城市”);
return;
}
$.ajax({
url: “/ajax/weather_forecast/forecast.php”,
type: “POST”,
data: {city_number:$(“#city”).val()},
dataType: “json”,
success: function (data){
var info = data.weatherinfo;
var $table = “<table class=’weather’ border=’1′><tr><th></th><th>今天</th><th>明天</th><th>后天</th></tr>”;
$table += “<tr><th>温度</th><td>”+info.temp1+”</td><td>”+info.temp2+”</td><td>”+info.temp3+”</td></tr>”;
$table += “<tr><th>天气</th><td>”+info.weather1+”</td><td>”+info.weather2+”</td><td>”+info.weather3+”</td></tr>”;
$table += “<tr><th>风速</th><td>”+info.wind1+”</td><td>”+info.wind2+”</td><td>”+info.wind3+”</td></tr>”;
$table += “<tr><th>风速级别</th><td>”+info.fl1+”</td><td>”+info.fl2+”</td><td>”+info.fl3+”</td></tr>”;
$table += “</table><br />”;
$table += “<table class=’index’ border=’1′><tr><th colspan=’3′>详细情况</th></tr>”;
$table += “<tr><th width=’20%’>今天穿衣指数</th><td width=’10%’>”+info.index+”</td><td width=’70%’>”+info.index_d+”</td></tr>”;
$table += “<tr><th>48小时穿衣指数</th><td>”+info.index48+”</td><td>”+info.index48_d+”</td></tr>”;
$table += “<tr><th>紫外线及48小时紫外线</th><td>”+info.index_uv+”</td><td>”+info.index48_uv+”</td></tr>”;
$table += “<tr><th>洗车</th><td colspan=’2′>”+info.index_xc+”</td></tr>”;
$table += “<tr><th>外出旅游</th><td colspan=’2′>”+info.index_tr+”</td></tr>”;
$table += “<tr><th>舒适指数</th><td colspan=’2′>”+info.index_co+”</td></tr>”;
$table += “<tr><th>晨练</th><td colspan=’2′>”+info.index_cl+”</td></tr>”;
$table += “<tr><th>晾晒</th><td colspan=’2′>”+info.index_ls+”</td></tr>”;
$table += “<tr><th>过敏</th><td colspan=’2′>”+info.index_ag+”</td></tr>”;
$table += “</table>”;
$(“#weather”).html($table);
}
});
});
});
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Strict//EN” “http://www.w3.org/TR/html4/strict.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>黄金价格走势</title>
<script type=”text/javascript” src=”../js/jquery-1.8.3.min.js”></script>
<script type=”text/javascript” src=”gold_price.js”></script>
</head>
<body>
<div align=”center”>
<h1>黄金价格走势</h1>
<h3>每隔5秒刷新页面,距下次刷新还有<font id=”sec”>5</font>秒</h3>
<table align=”center” width=”300px”>
<tr><td width=”30%”>市场</td><td width=”30%”>最新价格</td><td width=”40%”>涨跌</td></tr>
<tr id=”ld”><td width=”30%”>伦敦</td><td width=”30%”>0</td><td width=”40%”>0</td></tr>
<tr id=”tw”><td width=”30%”>台湾</td><td width=”30%”>0</td><td width=”40%”>0</td></tr>
<tr id=”dj”><td width=”30%”>东京</td><td width=”30%”>0</td><td width=”40%”>0</td></tr>
</table>
</div>
</body>
</html>
$(function (){
run();
//开启定时器
var interval = null;
var interval2 = null;
function run() {
if (interval == null) {
//设置定时器,每5秒钟执行getPrice函数一次
interval = setInterval(getPrice, “5000”);
}
if (interval2 == null) {
interval2 = setInterval(jishi, “1000”);
}
}
//停止定时器
function stop() {
if (interval != null)
clearTimeout(interval);
}
//发送ajax请求
function getPrice() {
$.ajax({
url: “/ajax/gold_price/price.php”,
type: “POST”,
data: {ld: $(“#ld td:eq(1)”).text(), tw: $(“#tw td:eq(1)”).text(), dj: $(“#dj td:eq(1)”).text()},
dataType: “json”,
success: function(data) {
//伦敦
$(“#ld > td:eq(1)”).text(data.ld.price);
var $value = “0”;
if (parseInt(data.ld.price_change) == 0) {
$value = “0”;
}else if (parseInt(data.ld.price_change) > 0) {
$value = “<img src=’up.png’ alt=’rise’>”+data.ld.price_change;
}else {
$value = “<img src=’down.png’ alt=’fall’>”+data.ld.price_change.substring(1);
}
$(“#ld > td:eq(2)”).html($value);
//台湾
$(“#tw > td:eq(1)”).text(data.tw.price);
var $value = “0”;
if (parseInt(data.tw.price_change) == 0) {
$value = “0”;
}else if (parseInt(data.tw.price_change) > 0) {
$value = “<img src=’up.png’ alt=’rise’>”+data.tw.price_change;
}else {
$value = “<img src=’down.png’ alt=’fall’>”+data.tw.price_change.substring(1);
}
$(“#tw > td:eq(2)”).html($value);
//东京
$(“#dj > td:eq(1)”).text(data.dj.price);
var $value = “0”;
if (parseInt(data.dj.price_change) == 0) {
$value = “0”;
}else if (parseInt(data.dj.price_change) > 0) {
$value = “<img src=’up.png’ alt=’rise’>”+data.dj.price_change;
}else {
$value = “<img src=’down.png’ alt=’fall’>”+data.dj.price_change.substring(1);
}
$(“#dj > td:eq(2)”).html($value);
}
});
}function jishi() {
var t = parseInt($(“#sec”).text());
if (t > 1) {
$(“#sec”).text(–t);
}else {
$(“#sec”).text(“0”);
$(“#sec”).text(“5”);
}
}
});
<?php
//设置返回的格式
header ( “Content-Type:text/html;charset=utf-8” );
//设置禁用缓存
header ( “Cache-Control:no-cache” );
//接收数据
ld_old =_POST[‘ld’];
tw_old =_POST[‘tw’];
dj_old =_POST[‘dj’];
//生成三个动态数据
ld = rand(500, 1500);tw = rand(500, 1500);
dj = rand(500, 1500);
//计算涨跌,发送结果info = ‘{“ld”:{“price”:”‘.ld.'”,”price_change”:”‘.(ld-ld_old).'”},’;info .= ‘”tw”:{“price”:”‘.tw.'”,”price_change”:”‘.(tw-tw_old).'”},’;info .= ‘”dj”:{“price”:”‘.dj.'”,”price_change”:”‘.(dj-dj_old).'”}}’;
//写会数据
echoinfo;
《基于PHP的AJAX学习笔记(教程)》有2个想法