Ajax缓存问题的解决:Ajax的本质就是将状态保存在客户端,因此资源的缓存和再利用是他的优势所在,但有时候不希望被缓存,例如计数器,不同请求的计数器得到的结果应该是最新的。在线时长也应该每次刷新不一样。
1)设置随机数: Math.random();
url: "user.php?username="+username+"&num="+Math.random();
2)设置时间戳
var dateTime = new Date().getTime()
url: "user.php?username="+username+"&num="+dateTime;
3)使用POST代替GET方式提交数据: POST本身提交和返回的数据的不缓存;
4)设置响应头信息
header("Cache-Control:no-cache");
POST方式数据传递:
1、在send前 设置post发送的数据按照URL地址方式传递
ajax.setRequestHeader("content-Type","application/x-www-form-urlencoded");
2、open函数中第二个参数只剩下提交地址
3、将传递的数据: 参数名=值&参数名=值&...的方式放入到send函数()中
ajax.open("POST","./user.php",false);
//发送
ajax.setRequestHeader("content-TYPE","application/x-www-form-urlencoded");
var data = "uname="+uname;
ajax.send(data);
reg.html
<!DOCTYPE HTML>
<html>
<head>
<title> ajax </title>
<meta charset="utf-8"/>
<script type="text/javascript">
var httpAjax = new XMLHttpRequest();
function checkUser(uname){
if(uname == ""){
return false;
}
httpAjax.onreadystatechange = function(){
if(httpAjax.readyState == 4 && httpAjax.status == 200){
var res = httpAjax.responseText;
var sp = document.getElementById("sp");
if(res == "true"){
sp.innerHTML = "<font color='red'>已注册</font>";
}else{
sp.innerHTML = "<font color='green'>可以注册</font>"
}
}
}
httpAjax.open("post","user.php",true);
httpAjax.setRequestHeader("content-TYPE","application/x-www-form-urlencoded");
var data = "uname="+uname; //user.php?uname="1"&pwd="123","uname=" 是参数,+是参数连接变量的用的,uname是js中的一个不带$的变量,也就是值
httpAjax.send(data);
}
</script>
</head>
<body>
<input type="text" id="username" class="username" name="username" οnchange="checkUser(this.value)"/><span id="sp"></span>
</body>
</html>
user.php
<?php
header("content-type:text/html;charset=utf-8");
$pdo = new PDO("mysql:host=localhost;dbname=tk106","root","");
$pdo->exec("set names utf8");
$uname = $_REQUEST["uname"];//post传值,这里要改为REQUEST接收
$sql = "select * from stu_info where sname='".$uname."'";
$data = $pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
if($data){
echo "true";
}else{
echo "false";
}
?>
转载于:https://blog.51cto.com/it5808/1715025