ajax中get和post的說明及使用與區別_javascript技巧

來源:互聯網
上載者:User
以前沒怎麼仔細的研究過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("xiaochengf_21@yahoo.com.cn");
xmlhttp.open("GET", "somepage" + "?" + postContent, true);
xmlhttp.send(null);

POST 方式
複製代碼 代碼如下:

var postContent ="name=" + encodeURIComponent("xiaocheng") + "&email=" + encodeURIComponent("xiaochengf_21@yahoo.com.cn");
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");這句代碼,不知道為什麼,初學,加了就能傳遞參數了,日後研究。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.