ajax与服务器传值有两种方式:get 和post的区别

        ajax与服务器传值有两种方式:get 和post,这两种传值方式到底有什么区别呢?请看下述:
        
  1. get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到。post是通过HTTP post机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程。get可以使用浏览器的缓存机制,别的用户可以从缓存中获取你的信息,比如“用户名和密码”,而POST获取不到,所以使用POST比较安全。
  2. 对于get方式,服务器端用Request.QueryString获取变量的值,对于post方式,服务器端用Request.Form获取提交的数据。两种方式的参数都可以用Request来获得。Servlet中使用request.getParameter(key)来获取值。
  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主体中的,其组织方式不只一种,有&连接方式,也有分割符方式,可隐藏参数,传递大批数据,比较方便。

        现在我们再看看通过URL发送请求时,get方式和post方式的区别。用下面的例子可以很容易的看到同样的数据通过GET和POST来发送的区别,发送的数据是 username=张三。

GET 方式,浏览器键入 http://localhost?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);  
get方式

get方式是最为常见的,一般实现用户登录,修改密码用的都是get方式。

新建一html文档,body标签内容如下:

<body style="text-align: center">
    <input type ="text" id ="txt" />
    <br />
    <input type ="button" value ="get方式回调"  onclick ="get()" />
</body>  

js代码文件

var xhr=getXHR();//获得xmlhttprequest对象,getXHR函数的具体实现这里不给出,因为非常简单
function get()
{
    var str=document.getElementById ("txt").value;
    var url="PageAjax.aspx?argument="+escape(str);//编码str
    xhr.open("get",url,true);
    xhr.onreadystatechange=renew;
    xhr.send(null);//不发送任何内容,因为url中包含了参数数据
}
function renew()
{
    if (xhr.readystate==4)
    {
        if (xhr.status==200)
        {
            var response=xhr.responsetext;
            var res=response.split('\n');
            alert(res[0]);
        }
    }
}  

服务器端PageAjax.aspx.cs文件代码如下

protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["argument"] != null)
        {
            string res ="成功实现post方式回调!传入的参数是:"+ Request["argument"].ToString()+"\n";
            Response.Write(res);
        }
    }  

到此一个简单的get方式回调完成。

post方式

由于get方式每次都要传入参数到url地址上,像用户名,密码之类的参数由于字符比较少,完全可以考虑这中传递方式,但是当有很多参数、并且参数的字符串值很长时(比如博客,你不可能把整篇博客的内容都以参数的方式传递到url上),这种方式就不好了,由于有了post方式的出现。

新建一html文档,body标签内容如下:

<textarea id="TextArea1" style="width: 323px; height: 76px"></textarea>
    <br />
    <input id="Button1" type="button" value="post方式回调" οnclick="post()" />  

js代码文件

var xhr=getXHR();//获得xmlhttprequest对象,getXHR函数的具体实现这里不给出,因为非常简单
function post() 
{
    var str=document.getElementById ("TextArea1").value;
    var poststr="arg="+str;
    var url="PageAjax.aspx?time="+new Date();//加一时间戳,放置发回的数据是服务器缓存的数据
    xhr.open("post",url,true);
   
    xhr.onreadystatechange=update;
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //告诉服务器发送的是文本
    //xhr.setRequestHeader("Content-Type", "text/xml"); //告诉服务器发送的是一个xml文件
xhr.send(poststr);//发送poststr数据到服务器}function update(){ if (xhr.readystate==4) { if (xhr.status==200) { var response=xhr.responsetext; var res=response.split('\n'); alert(res[0]); } }}

服务器端PageAjax.aspx.cs文件代码如下

protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["arg"] != null)
        {
            string res = "成功实现get方式回调!传入的参数是:" + Request["arg"].ToString() + "\n";
            Response.Write(res);
        }
    }  

到此一个简单的post方式回调完成。

Get 与 Post 的代码编写上的区别

.......  
function createQueryString(){  
 var firstName = document.getElementById("firstName").value;  
 var secName = document.getElementById("secName").value;  
  
 var querystring="firstName="+firstName+"&secName="+secName;  
}  
  
  
//GET方式  
function doRequestUsingGET(){  
   createXMLHttpRequest();  
   var queryString = "test.php?";  
   queryString= queryString + createQueryString()+"&timstamp="+new Date().getTime();  
   Ajax.onreadystatechange=handleStateChange;  
   Ajax.open("GET",queryString,true);  
   Ajax.send(null);  
  
}  
  
//POST方式  
function doRequestUsingPOST(){  
   createXMLHttpRequest();  
  
  /* 注意以下代码与GET方式的区别 */  
   var url= "test.php?timstamp="+new Date().getTime();  
   // POST 需要定义发送的字符串
   var queryString=createQueryString();
   Ajax.open("POST",url,true);  
   Ajax.onreadystatechange=handleStateChange;  
   // POST 需要设置请求头部
   Ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded")  
   // 参数不为 null 
   Ajax.send(queryString);  
  
}  
  
function handleStateChange(){  
    if(Ajax.readyState==4){  
       if(Ajax.status==200){ .......}   //成功数据其它数据  
    }  
  
}  
下面看一个例子:
    使用jsp+Ajax+ Servlet实现异步传输:
    客户端代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<html>
	<head>
		<title>Ajax</title>
		<script type="text/javascript">
	function loadXMLDoc() {
		if (document.getElementById("account").value == "") {
			document.getElementById("accDiv").innerHTML = "用户名不能为空";
			return;
		}

//先实例化一个XMLHttpReques对象,根据不同的浏览器的不同设置不同的实例化构造方法;
		var xmlHttp;
		if (window.XMLHttpRequest) {                // IE版本7以上
			xmlHttp = new XMLHttpRequest();
		} else {                                    // IE版本5和IE版本6
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}

//当onreadystatechange发生改变时执行function()
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
//xmlHttp.responseText  responseText是获取到服务器返回的数据
				document.getElementById("accDiv").innerHTML = xmlHttp.responseText;
			}
		}
		var a = document.getElementById("account").value;
		var url = "validate?";
		var transData = "name=" + encodeURI(a);

		xmlHttp.open("POST", url, true);
//若使用POST进行传值,则必须加上下面的语句,进行请求参数声明。
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
//将要传送的参数使用send(String data)传送;
		xmlHttp.send(transData);
	}
	function delData() {
		document.getElementById("account").value = "";
		document.getElementById("accDiv").innerHTML = "";
	}
</script>
<style type="text/css">
#accDiv {
	font-family: 楷体;
	font-size: 14px;
	color: #FF0000;
}
</style>
	</head>
	<body>
		<h3>
			ajax
		</h3>
		<table>
			<tr>
				<td>
					账号:
				</td>
				<td>
					<input id="account" type="text" οnblur="loadXMLDoc();"
						οnfοcus="delData();" />
				</td>
				<td>
					<div id="accDiv"></div>
				</td>
			</tr>
			<tr>
				<td>
					密码:
				</td>
				<td>
					<input id="passwd" type="password" />
				</td>
			</tr>
			<tr>
				<td>
					确认密码:
				</td>
				<td>
					<input id="vPasswd" type="password" />
				</td>
			</tr>
			<tr>
				<td>
					姓名:
				</td>
				<td>
					<input id="name" type="text" />
				</td>
			</tr>
		</table>

	</body>
</html>
服务器端:
public class validate extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

 //因为使用POST传值,所以要使用doPost进行接收
public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

 //此处必须加,如不,则客户端获取的返回值会是乱码。
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
//接受数据时,需要将传过来的数据编码转换成utf-8;就可以接收数据,不会再出现乱码。
		String name = new String(request.getParameter("name").getBytes(
				"ISO-8859-1"), "utf-8");
		System.out.println(name);
		out.print(name);
	}

}

  
  


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值