ajax POST方式數據傳遞

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" 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";
	}
?>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章