Ajax 的 GET 和 POST 模式
Ajax 异步请求数据的方式有两种:GET 和 POST。
如果是 GET 模式,则直接将数据放置到异步请求的 URL 地址中,而 send() 方法不发送任何数据;
1 var queryString = "name=Liruxing&sex=man"; 2 var url = "index.php" + queryString + "time=" + new Date().getTime(); 3 xmlHttp.open('GET',url); 4 xmlHttp.send(null);
如果是 POST 模式,则将数据放置在 send() 方法中发送。
1 var queryString = "name=Liruxing&sex=man"; 2 var url = "index.php" + new Date().getTime(); 3 xmlHttp.open('POST',url); 4 xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 5 xmlHttp.send(queryString);
下面的示例能够更清楚的演示 GET 模式和 POST 模式的区别(Ajax 结合 PHP)
index.html
1 <html> 2 <head> 3 <title>Ajax</title> 4 <script language="javascript"> 5 var xmlHttp; 6 // 创建 XMLHttpRequest 7 function createXMLHttpRequest() { 8 if (window.ActiveXObject) { 9 xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); 10 } else if (window.XMLHttpRequest) { 11 xmlHttp = new XMLHttpRequest(); 12 } 13 } 14 15 function createQueryString() { 16 var name = document.getElementById('name').value; 17 var sex = document.getElementById('sex').value; 18 var queryString = "name="+ name +"&sex=" + sex; 19 return encodeURI(encodeURI(queryString)); // 两次编码解决中文乱码问题 20 } 21 22 function handleStateChange() { 23 if (xmlHttp.readyState==4 && xmlHttp.status==200) { 24 var content = document.getElementById("content"); 25 content.innerHTML = ''; 26 content.innerHTML = decodeURI(xmlHttp.responseText); // 解码 27 } 28 } 29 30 // GET 方法 31 function doRequestUsingGet() { 32 createXMLHttpRequest(); 33 var url = "index.php?" + createQueryString() + "&time=" + new Date().getTime(); 34 xmlHttp.open('GET', url); 35 xmlHttp.onreadystatechange = handleStateChange; 36 xmlHttp.send(null); 37 } 38 39 // POST 方法 40 function doRequestUsingPost() { 41 createXMLHttpRequest(); 42 var url = "index.php?time=" + new Date().getTime(); 43 var queryString = createQueryString(); 44 xmlHttp.open('POST', url); 45 xmlHttp.onreadystatechange = handleStateChange; 46 xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 47 xmlHttp.send(queryString); 48 } 49 </script> 50 </head> 51 <body> 52 <p>Name:<input type="text" id="name" /></p> 53 <p>Sex :<input type="text" id="sex" /></p> 54 <p><input type="button" value="GET" onClick="doRequestUsingGet()"> <input type="button" value="POST" onClick="doRequestUsingPost()"></p> 55 <div id="content"></div> 56 </body> 57 </html>
index.php:
1 <?php 2 header('Content-Type:text/html;Charset=GB2312'); 3 $method = $_SERVER['REQUEST_METHOD']; 4 if ($method == 'GET') { 5 echo "GET:".$_GET['name'].",".$_GET['sex']; 6 } else if ($method == 'POST') { 7 echo "POST:".$_POST['name'].",".$_POST['sex']; 8 } 9 ?>