Ajax緩存問題的解決:Ajax的本質就是將狀態保存在客戶端,所以資源的緩存和再利用是他的優點所在,但有時候不但願被緩存,例如計數器,不一樣請求的計數器獲得的結果應該是最新的。在線時長也應該每次刷新不同。javascript
1)設置隨機數: Math.random();php
url: "user.php?username="+username+"&num="+Math.random(); html
2)設置時間戳java
var dateTime = new Date().getTime() mysql
url: "user.php?username="+username+"&num="+dateTime;ajax
3)使用POST代替GET方式提交數據: POST自己提交和返回的數據的不緩存; sql
4)設置響應頭信息緩存
header("Cache-Control:no-cache");app
POST方式數據傳遞:dom
一、在send前 設置post發送的數據按照URL地址方式傳遞
ajax.setRequestHeader("content-Type","application/x-www-form-urlencoded");
二、open函數中第二個參數只剩下提交地址
三、將傳遞的數據: 參數名=值&參數名=值&...的方式放入到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" onchange="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"; } ?>