本文執行個體分析了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() + "×tamp=" + 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" id="firstName" /><br> <input type="text" id="birthday" /></form><form> <input type="button" value="GET" onclick="doRequestUsingGET();" /><br> <input type="button" value="POST" onclick="doRequestUsingPOST();" /></form><div id="serverResponse"></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 模式的請求。
希望本文所述對大家的Ajax程式設計有所協助。