onreadystatechange

responseText将响应信息作为字符串返回。
responseXML将响应信息作为XML文档返回。
send发送请求到http服务器并返回。
setRequestHeader单独制定请求的某个http头
status返回当前请求的http状态码
readyState返回xmlHttp请求的当前状态(对象本身的状态)
XMLHttpRequest提供客户端同http服务器通讯的协议(该对象是和浏览器本身相关的,不同浏览器创建的方式不一样)。
glodPrice.php
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<script language="javascript" type="text/javascript">
var myXmlHttpRequest;
function updateGoldPrice(){
myXmlHttpRequest=getXmlHttpObject();
if(myXmlHttpRequest){
//创建ajax引擎对象成功
//window.alert("ok");
var url="glodPriceProcess.php";
var data="city[]=dj&city[]=tw&city[]=ld";
myXmlHttpRequest.open("post",url,true);
myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
myXmlHttpRequest.onreadystatechange=function chuli(){
//接收数据json
//readyState=4只能代表完成,不表示成功了。
if(myXmlHttpRequest.readyState==4){
if(myXmlHttpRequest.status==200){
//取出数据,进行处理
//window.alert("ok");
//取出并转成对象数组
var res_objects=eval("("+myXmlHttpRequest.responseText+")");
$(‘dj‘).innerText=res_objects[0].price;
if(res_objects[0].price>1000){
djimg.src="up.png";
}else{
djimg.src="down.png";
}
$(‘tw‘).innerText=res_objects[1].price;
if(res_objects[1].price>1000){
twimg.src="up.png";
}else{
twimg.src="down.png";
}
$(‘ld‘).innerText=res_objects[2].price;
if(res_objects[2].price>1000){
ldimg.src="up.png";
}else{
ldimg.src="down.png";
}
}
}
}
myXmlHttpRequest.send(data);
}
}
//使用定时器 每隔5秒
window.setInterval("updateGoldPrice()",5000);
</script>
<script language="javascript" type="text/javascript" src="my.js">
</script>
</head>
<center>
<h1>每隔5秒钟更新数据(以1000为基数计算涨跌)</h1>
<table border="0" style="border:2px solid pink">
<tr><td colspan="3"><img src="bg.png"/></td></tr>
<tr><td>市场</td><td>最新价格$</td><td>涨跌</td></tr>
<tr><td>伦敦</td><td id="ld">788.7</td><td><img src="down.png" id="ldimg"/>211.3</td></tr>
<tr><td>台湾</td><td id="tw">854.0</td><td><img src="down.png" id="twimg"/>146.0</td></tr>
<tr><td>东京</td><td id="dj">1791.3</td><td><img src="up.png" id="djimg"/>791.3</td></tr>
</table>
</center>
</html>
glodPriceProcess.php
<?php //这里两句话很重要,第一句话告诉浏览器返回的数据是xml格式 header("Content-type: text/html; charset=utf-8"); //如果这里写成Content-type: text/html,会报错,得不到数据 //告诉浏览器不要缓存数据 header("Cache-Control:no-cache"); //接收 $cities=$_POST[‘city‘]; //随机地生成 三个 500-2000的数 $res=‘[{"price":"400"},{"price":"1000"},{"price":"1200"}]‘; $res=‘[‘; for($i=0;$i<count($cities);$i++){ if($i==count($cities)-1){ $res.=‘{"cityname":"‘.$cities[$i].‘","price":"‘.rand(500,1500).‘"}]‘; }else{ $res.=‘{"cityname":"‘.$cities[$i].‘","price":"‘.rand(500,1500).‘"},‘; } } file_put_contents("D:/install/wamp/www/mylog.log",$res."\r\n",FILE_APPEND); echo $res; ?>
使用ajax与服务器通信的步骤
①创建一个XMLHttpRequest对象
②创建url.data,通过xmlHttpRequest.send()
③服务器接收ajax的请求,做相应处理(操作数据库),然后返回结果(echo 语句)
④客户端通过xmlHttpRequest的属性responseText,responseXML取的数据,然后就完成局部刷新当前页面任务。
原文:https://www.cnblogs.com/liaoxiaolao/p/9819617.html