AJAX使用get与post模式的区别分析

如果是get 模式的请求,则将传递参数通过URL 地址发送到服务器端;

如果是post 模式的请求,则将传递参数通过send( ) 方法发送到服务器端(并且必须设置请求文件头);

post 模式的代码如下:

<script type="text/javascript"> <!-- var queryString = "firstName=xugang&birthday=1227"; var url = "9-3.aspx?timetamp=" + new Date().getTime(); xmlHttp.open("POST",url); xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlHttp.send(queryString); //该语句负责发送数据 //--> </script>

一个演示get 模式与post 模式区别的示例:

客户端:

代码示例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>GET VS. POST</title> <script language="javascript"> var xmlHttp; function createXMLHttpRequest(){ if(window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHttp"); else if(window.XMLHttpRequest) xmlHttp = new XMLHttpRequest(); } function createQueryString(){ var firstName = document.getElementById("firstName").value; var birthday = document.getElementById("birthday").value; var queryString = "firstName=" + firstName + "&birthday=" + birthday; return encodeURI(encodeURI(queryString)); //两次编码解决中文乱码问题 } // GET 模式 function doRequestUsingGET(){ createXMLHttpRequest(); var queryString = "9-3.aspx?"; queryString += createQueryString() + "&timestamp=" + new Date().getTime(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open("GET",queryString); xmlHttp.send(null); } // POST 模式 function doRequestUsingPOST(){ createXMLHttpRequest(); var url = "9-3.aspx?timestamp=" + new Date().getTime(); var queryString = createQueryString(); xmlHttp.open("POST",url); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlHttp.send(queryString); } function handleStateChange(){ if(xmlHttp.readyState == 4 && xmlHttp.status == 200){ var responseDiv = document.getElementById("serverResponse"); responseDiv.innerHTML = decodeURI(xmlHttp.responseText);//解码 } } </script> </head> <body> <h2>输入姓名和生日</h2> <form> <input type="text" /><br> <input type="text" /> </form> <form> <input type="button" value="GET" /><br> <input type="button" value="POST" /> </form> <div></div> </body> </html>

服务器端

代码示例:

复制代码 代码如下:

<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312" %>
<%@ Import Namespace="System.Data" %>
<%
    if(Request.HttpMethod == "POST")
        Response.Write("POST: " + Request["firstName"] + ", your birthday is " + Request["birthday"]);
    else if(Request.HttpMethod == "GET")
        Response.Write("GET: " + Request["firstName"] + ", your birthday is " + Request["birthday"]);
%>

通常在数据不多,并且不敏感的时候,使用get 模式的请求;

而数据量大,或者数据敏感的时候,使用post 模式的请求。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wfyxwp.html