DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> ajax中get和post的說明及使用與區別
ajax中get和post的說明及使用與區別
編輯:關於JavaScript     
以前沒怎麼仔細的研究過ajax,只是用到了就直接拿過來用,發現了問題再找解決方法.以下是我在找解決問題的過程中的一點小小的總結.

一.談Ajax的Get和Post的區別
Get方式:
用get方式可傳送簡單數據,但大小一般限制在1KB下,數據追加到url中發送(http的header傳送),也就是說,浏覽器將各個表單字段元素及其數據按照URL參數的格式附加在請求行中的資源路徑後面。另外最重要的一點是,它會被客戶端的浏覽器緩存起來,那麼,別人就可以從浏覽器的歷史記錄中,讀取到此客戶的數據,比如帳號和密碼等。因此,在某些情況下,get方法會帶來嚴重的安全性問題。
Post方式:
當使用POST方式時,浏覽器把各表單字段元素及其數據作為HTTP消息的實體內容發送給Web服務器,而不是作為URL地址的參數進行傳遞,使用POST方式傳遞的數據量要比使用GET方式傳送的數據量大的多。
總之,GET方式傳送數據量小,處理效率高,安全性低,會被緩存,而POST反之。

使用get方式需要注意
1 對於get請求(或凡涉及到url傳遞參數的),被傳遞的參數都要先經encodeURIComponent方法處理.例:var url = "update.php?username=" +encodeURIComponent(username) + "&content=" +encodeURIComponent
(content)+"&id=1" ;
使用Post方式需注意
1.設置header的Context-Type為application/x-www-form-urlencode確保服務器知道實體中有參數變量.通常使用XmlHttpRequest對象的SetRequestHeader("Context-Type","application/x-www-form-urlencoded;")。例:
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
2.參數是名/值一一對應的鍵值對,每對值用&號隔開.如 var name=abc&sex=man&age=18,注意var name=update.php?
abc&sex=man&age=18以及var name=?abc&sex=man&age=18的寫法都是錯誤的;
3.參數在Send(參數)方法中發送,例: xmlHttp.send(name); 如果是get方式,直接 xmlHttp.send(null);
4.服務器端請求參數區分Get與Post。如果是get方式則$username = $_GET["username"]; 如果是post方式,則$username = $_POST["username"];

Post和Get 方法有如下區別:
1.Post傳輸數據時,不需要在URL中顯示出來,而Get方法要在URL中顯示。
2.Post傳輸的數據量大,可以達到2M,而Get方法由於受到URL長度的限制,只能傳遞大約1024字節.
3.Post顧名思義,就是為了將數據傳送到服務器段,Get就是為了從服務器段取得數據.而Get之所以也能傳送數據,只是用來設計告訴服務器,你到底需要什麼樣的數據.Post的信息作為http請求的內容,而Get是在Http頭部傳輸的。
get 方法用Request.QueryString["strName"]接收
post 方法用Request.Form["strName"] 接收
注意:
雖然兩種提交方式可以統一用Request("strName")來獲取提交數據,但是這樣對程序效率有影響,不推薦使用。
一般來說,盡量避免使用Get方式提交表單,因為有可能會導致安全問題

AJAX亂碼問題
產生亂碼的原因:
1、xtmlhttp 返回的數據默認的字符編碼是utf-8,如果客戶端頁面是gb2312或者其它編碼數據就會產生亂碼
2、post方法提交數據默認的字符編碼是utf-8,如果服務器端是gb2312或其他編碼數據就會產生亂碼

解決辦法有
1、若客戶端是gb2312編碼,則在服務器指定輸出流編碼
2、服務器端和客戶端都使用utf-8編碼
gb2312:header('Content-Type:text/html;charset=GB2312');
utf8:header('Content-Type:text/html;charset=utf-8');
注意:如果你已經按上面的方法做了,還是返回亂碼的話,檢查你的方式是否為get,對於get請求(或凡涉及到url傳遞參數的),被傳遞的參數都要先經encodeURIComponent方法處理.如果沒有用encodeURIComponent處理的話,也會產生亂碼.
下邊是我找到的一個例子,因為寫的不錯就貼在這裡了,自己寫的比較簡單,也不是很規范還是參考人家寫的好了,呵呵!
復制代碼 代碼如下:
var http_request = false;
function makePOSTRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//alert(http_request.responseText);
result = http_request.responseText;
document.getElementById('myspan').innerHTML = result;
} else {
alert('There was a problem with the request.');
}
}
}
function get(obj) {
var poststr = "mytextarea1=" + encodeURI( document.getElementById("mytextarea1").value ) +
"&mytextarea2=" + encodeURI( document.getElementById("mytextarea2").value );
makePOSTRequest('post.php', poststr);
}

post.php
<?print_r($_POST);?>一個超大文本框textarea裡面有大量數據,ajax通過URL請求service返回結果,URL裡面包含了各種參數,當然也包含之前的超大文本框的內容。 之前開發的時候一直用Firefox在調試,4000長度的字符串在textarea裡面通過URL請求都是沒有問題。 提交給測試的時候問題來了,測試人員在IE下面發現問題,textarea裡面字符長度超過2000(大概數據)時,會報JS錯誤,ajax沒有返回值給前台。 看原先代碼:
復制代碼 代碼如下:
function getJsonData(url)
{
var ajax = Common.createXMLHttpRequest();
ajax.open("GET",url,false);
ajax.send(null);
try
{
eval("var s = "+ajax.responseText);
return s;
}
catch(e)
{
return null;
}
}
function getData(){
var url="BlacklistService.do?datas="+datasvalue;
var result = getJsonData(url);
}

網上google發現解決辦法: 修改使用的XMLHttp的請求為POST,並且把參數和URL分離出來提交。 修改後代碼如下:
復制代碼 代碼如下:
function getJsonData(url,para)
{
var ajax = Common.createXMLHttpRequest();
ajax.open("POST",url,false);
ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
ajax.send(para);
try
{
eval("var s = "+ajax.responseText);
return s;
}
catch(e)
{
return null;
}
}
function getData(){
var url="BlacklistService.do";
var para="datas="+datasvalue;
var result = getJsonData(url,para);
}

================================
Ajax中的get和post兩種請求方式的異同2008年10月04日 星期六 下午 02:37分析兩種提交方式的異同Ajax中我們經常用到get和post請求.那麼什麼時候用get請求,什麼時候用post方式請求呢? 在做回答前我們首先要了解get和post的區別.
1、 get是把參數數據隊列加到提交表單的ACTION屬性所指的URL中,值和表單內各個字段一一對應,在URL中可以看到。post是通過HTTP post機制,將表單內各個字段與其內容放置在HTML HEADER內一起傳送到ACTION屬性所指的URL地址。用戶看不到這個過程。
2、 對於get方式,服務器端用Request.QueryString獲取變量的值,對於post方式,服務器端用Request.Form獲取提交的數據。兩種方式的參數都可以用Request來獲得。
3、get傳送的數據量較小,不能大於2KB。post傳送的數據量較大,一般被默認為不受限制。但理論上,因服務器的不同而異.
4、get安全性非常低,post安全性較高。
5、 <form method="get" action="a.asp?b=b">跟<form method="get" action="a.asp">是一樣的,也就是說,method為get時action頁面後邊帶的參數列表會被忽視;而<form method="post" action="a.asp?b=b">跟<form method="post" action="a.asp">是不一樣的。另外 Get請求有如下特性:它會將數據添加到URL中,通過這種方式傳遞到服務器,通常利用一個問號?代表URL地址的結尾與數據參數的開端,後面的參數每一個數據參數以“名稱=值”的形式出現,參數與參數之間利用一個連接符&來區分。 Post請求有如下特性:數據是放在HTTP主體中的,其組織方式不只一種,有&連接方式,也有分割符方式,可隱藏參數,傳遞大批數據,比較方便。通過以上的說明,現在我們大致了解了什麼時候用get什麼時候用post方式了吧,對!當我們在提交表單的時候我們通常用post方式,當我們要傳送一個較大的數據文件時,需要用post。當傳遞的值只需用參數方式(這個值不大於2KB)的時候,用get方式即可。現在我們再看看通過URL發送請求時,get方式和post方式的區別。用下面的例子可以很容易的看到同樣的數據通過GET和POST來發送的區別, 發送的數據是 username=張三 :
復制代碼 代碼如下:
GET /?username=%E5%BC%A0%E4%B8%89 HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)
Host: localhost
Connection: Keep-Alive
POST 方式:
POST / HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*
Accept-Language: zh-cn
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)
Host: localhost
Content-Length: 28
Connection: Keep-Alive
username=%E5%BC%A0%E4%B8%89

區別就是一個在 URL 請求裡面附帶了表單參數和值, 一個是在 HTTP 請求的消息實體中。比較一下上面的兩段文字, 我們會發現 GET 方式把表單內容放在前面的請求頭中, 而 POST 則把這些內容放在請求的主體中了, 同時 POST 中把請求的 Content-Type 頭設置為 application/x-www-form-urlencoded. 而發送的正文都是一樣的, 可以這樣來構造一個表單提交正文: encodeURIComponent(arg1)=encodeURIComponent(value1)&encodeURIComponent(arg2)=encodeURIComponent(value2)&.....注: encodeURIComponent 返回一個包含了 charstring 內容的新的 String 對象(Unicode 格式), 所有空格、標點、重音符號以及其他非 ASCII 字符都用 %xx 編碼代替,其中 xx 等於表示該字符的十六進制數。 例如,空格返回的是 "%20" 。 字符的值大於 255 的用 %uxxxx 格式存儲。參見 JavaScript 的 encodeURIComponent() 方法.在了解了上面的內容後我們現在用ajax的XMLHttpRequest對象向服務器分別用GET和POST方式發送一些數據。

GET 方式
復制代碼 代碼如下:
var postContent ="name=" + encodeURIComponent("xiaocheng") + "&email=" + encodeURIComponent("[email protected]");
xmlhttp.open("GET", "somepage" + "?" + postContent, true);
xmlhttp.send(null);

POST 方式
復制代碼 代碼如下:
var postContent ="name=" + encodeURIComponent("xiaocheng") + "&email=" + encodeURIComponent("[email protected]");
xmlhttp.open("POST", "somepage", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//xmlhttp.setRequestHeader("Content-Type", "text/xml"); //如果發送的是一個xml文件
xmlhttp.send(postContent);


Ajax的post方法的使用.
剛開始學Ajax,看到很多網上的代碼都用Get方法提交參數,Tomcat默認ISO編碼實在是讓人頭痛 ,對付亂碼我都是用過濾器做字符編碼過濾的,Get方法過濾器監聽不到,所以我一直喜歡使用Post方法,下面對Ajax Get和Post方法做一對比
GET
復制代碼 代碼如下:
<mce:script type="text/javascript"><!--
var xmlHttpRequest;
function createXMLHttpRequest(){
try
{
// Firefox, Opera 8.0+, Safari
xmlHttpRequest=new XMLHttpRequest();
}
catch (e)
{

// Internet Explorer
try
{
xmlHttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{

try
{
xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("您的浏覽器不支持AJAX!");
return false;
}
}
}

}
//發送請求函數
function sendRequestPost(url,param){
createXMLHttpRequest();
xmlHttpRequest.open("GET",url+"?"+param,true);
xmlHttpRequest.onreadystatechange = processResponse;
}
//處理返回信息函數
function processResponse(){
if(xmlHttpRequest.readyState == 4){
if(xmlHttpRequest.status == 200){
var res = xmlHttpRequest.responseText;
window.alert(res);
}else{
window.alert("請求頁面異常");
}
}
}
//身份驗證函數
function userCheck(){
var userName = document.loginForm.username.value;
var psw = document.loginForm.password.value;
if(userName == ""){
window.alert("用戶名不能為空");
document.loginForm.username.focus();
return false;
}
else{
var url = "Servlet/userLogin_do";
var param = "userName="+userName+"&psw="+psw;
sendRequestPost(url,param);
}
}
// --></mce:script>
<mce:script type="text/javascript"><!--
var xmlHttpRequest;
function createXMLHttpRequest(){
try
{
// Firefox, Opera 8.0+, Safari
xmlHttpRequest=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("您的浏覽器不支持AJAX!");
return false;
}
}
}
}
//發送請求函數
function sendRequestPost(url,param){
createXMLHttpRequest();
xmlHttpRequest.open("GET",url+"?"+param,true);
xmlHttpRequest.onreadystatechange = processResponse;
}
//處理返回信息函數
function processResponse(){
if(xmlHttpRequest.readyState == 4){
if(xmlHttpRequest.status == 200){
var res = xmlHttpRequest.responseText;
window.alert(res);
}else{
window.alert("請求頁面異常");
}
}
}
//身份驗證函數
function userCheck(){
var userName = document.loginForm.username.value;
var psw = document.loginForm.password.value;
if(userName == ""){
window.alert("用戶名不能為空");
document.loginForm.username.focus();
return false;
}
else{
var url = "Servlet/userLogin_do";
var param = "userName="+userName+"&psw="+psw;
sendRequestPost(url,param);
}
}
// --></mce:script>

POST
復制代碼 代碼如下:
<mce:script type="text/javascript"><!--
var xmlHttpRequest;
function createXMLHttpRequest(){
try
{
// Firefox, Opera 8.0+, Safari
xmlHttpRequest=new XMLHttpRequest();
}
catch (e)
{

// Internet Explorer
try
{
xmlHttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{

try
{
xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("您的浏覽器不支持AJAX!");
return false;
}
}
}

}
//發送請求函數
function sendRequestPost(url,param){
createXMLHttpRequest();
xmlHttpRequest.open("POST",url,true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-
urlencoded");
xmlHttpRequest.onreadystatechange = processResponse;
xmlHttpRequest.send(param);
}
//處理返回信息函數
function processResponse(){
if(xmlHttpRequest.readyState == 4){
if(xmlHttpRequest.status == 200){
var res = xmlHttpRequest.responseText;
window.alert(res);
}else{
window.alert("請求頁面異常");
}
}
}
//身份驗證函數
function userCheck(){
var userName = document.loginForm.username.value;
var psw = document.loginForm.password.value;
if(userName == ""){
window.alert("用戶名不能為空");
document.loginForm.username.focus();
return false;
}
else{
//var url = "Servlet/userLogin_do?userName="+userName+"&psw="+psw;
var url = "Servlet/userLogin_do";
var param = "userName="+userName+"&psw="+psw;
sendRequestPost(url,param);
}
}
// --></mce:script>
<mce:script type="text/javascript"><!--
var xmlHttpRequest;
function createXMLHttpRequest(){
try
{
// Firefox, Opera 8.0+, Safari
xmlHttpRequest=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("您的浏覽器不支持AJAX!");
return false;
}
}
}
}
//發送請求函數
function sendRequestPost(url,param){
createXMLHttpRequest();
xmlHttpRequest.open("POST",url,true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-
form-urlencoded");
xmlHttpRequest.onreadystatechange = processResponse;
xmlHttpRequest.send(param);
}
//處理返回信息函數
function processResponse(){
if(xmlHttpRequest.readyState == 4){
if(xmlHttpRequest.status == 200){
var res = xmlHttpRequest.responseText;
window.alert(res);
}else{
window.alert("請求頁面異常");
}
}
}
//身份驗證函數
function userCheck(){
var userName = document.loginForm.username.value;
var psw = document.loginForm.password.value;
if(userName == ""){
window.alert("用戶名不能為空");
document.loginForm.username.focus();
return false;
}
else{
//var url = "Servlet/userLogin_do?
userName="+userName+"&psw="+psw;
var url = "Servlet/userLogin_do";
var param = "userName="+userName+"&psw="+psw;
sendRequestPost(url,param);
}
}
// --></mce:script>

可以發現,GET方法根據地址欄解析參數,post根據sendRequestPost(url,param);中的param字符串解析參數,重要的是POST方法中需要添加在open();方法後需要添加xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");這句代碼,不知道為什麼,初學,加了就能傳遞參數了,日後研究。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved