zl程序教程

您现在的位置是:首页 >  前端

当前栏目

ajax中get和post的说明及使用与区别

AJAX 使用 说明 区别 get post
2023-06-13 09:14:42 时间
以前没怎么仔细的研究过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方法处理.例:varurl="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.参数是名/值一一对应的键值对,每对值用&号隔开.如varname=abc&sex=man&age=18,注意varname=update.php?
abc&sex=man&age=18以及varname=?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处理的话,也会产生乱码.
下边是我找到的一个例子,因为写的不错就贴在这里了,自己写的比较简单,也不是很规范还是参考人家写的好了,呵呵!
复制代码代码如下:

varhttp_request=false;
functionmakePOSTRequest(url,parameters){
http_request=false;
if(window.XMLHttpRequest){//Mozilla,Safari,...
http_request=newXMLHttpRequest();
if(http_request.overrideMimeType){
//settypeaccordinglytoanticipatedcontenttype
//http_request.overrideMimeType("text/xml");
http_request.overrideMimeType("text/html");
}
}elseif(window.ActiveXObject){//IE
try{
http_request=newActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
http_request=newActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
if(!http_request){
alert("CannotcreateXMLHTTPinstance");
returnfalse;
}
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);
}
functionalertContents(){
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("Therewasaproblemwiththerequest.");
}
}
}
functionget(obj){
varpoststr="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没有返回值给前台。看原先代码:
复制代码代码如下:

functiongetJsonData(url)
{
varajax=Common.createXMLHttpRequest();
ajax.open("GET",url,false);
ajax.send(null);
try
{
eval("vars="+ajax.responseText);
returns;
}
catch(e)
{
returnnull;
}
}
functiongetData(){
varurl="BlacklistService.do?datas="+datasvalue;
varresult=getJsonData(url);
}

网上google发现解决办法:修改使用的XMLHttp的请求为POST,并且把参数和URL分离出来提交。修改后代码如下:
复制代码代码如下:
functiongetJsonData(url,para)
{
varajax=Common.createXMLHttpRequest();
ajax.open("POST",url,false);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(para);
try
{
eval("vars="+ajax.responseText);
returns;
}
catch(e)
{
returnnull;
}
}
functiongetData(){
varurl="BlacklistService.do";
varpara="datas="+datasvalue;
varresult=getJsonData(url,para);
}

================================
Ajax中的get和post两种请求方式的异同2008年10月04日星期六下午02:37分析两种提交方式的异同Ajax中我们经常用到get和post请求.那么什么时候用get请求,什么时候用post方式请求呢?在做回答前我们首先要了解get和post的区别.
1、get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到。post是通过HTTPpost机制,将表单内各个字段与其内容放置在HTMLHEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程。
2、对于get方式,服务器端用Request.QueryString获取变量的值,对于post方式,服务器端用Request.Form获取提交的数据。两种方式的参数都可以用Request来获得。
3、get传送的数据量较小,不能大于2KB。post传送的数据量较大,一般被默认为不受限制。但理论上,因服务器的不同而异.
4、get安全性非常低,post安全性较高。
5、<formmethod="get"action="a.asp?b=b">跟<formmethod="get"action="a.asp">是一样的,也就是说,method为get时action页面后边带的参数列表会被忽视;而<formmethod="post"action="a.asp?b=b">跟<formmethod="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%89HTTP/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;MSIE6.0;WindowsNT5.0;.NETCLR1.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;MSIE6.0;WindowsNT5.0;.NETCLR1.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方式
复制代码代码如下:
varpostContent="name="+encodeURIComponent("xiaocheng")+"&email="+encodeURIComponent("xiaochengf_21@yahoo.com.cn");
xmlhttp.open("GET","somepage"+"?"+postContent,true);
xmlhttp.send(null);

POST方式
复制代码代码如下:
varpostContent="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方法,下面对AjaxGet和Post方法做一对比
GET
复制代码代码如下:
<mce:scripttype="text/javascript"><!--
varxmlHttpRequest;
functioncreateXMLHttpRequest(){
try
{
//Firefox,Opera8.0+,Safari
xmlHttpRequest=newXMLHttpRequest();
}
catch(e)
{

//InternetExplorer
try
{
xmlHttpRequest=newActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{

try
{
xmlHttpRequest=newActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("您的浏览器不支持AJAX!");
returnfalse;
}
}
}

}
//发送请求函数
functionsendRequestPost(url,param){
createXMLHttpRequest();
xmlHttpRequest.open("GET",url+"?"+param,true);
xmlHttpRequest.onreadystatechange=processResponse;
}
//处理返回信息函数
functionprocessResponse(){
if(xmlHttpRequest.readyState==4){
if(xmlHttpRequest.status==200){
varres=xmlHttpRequest.responseText;
window.alert(res);
}else{
window.alert("请求页面异常");
}
}
}
//身份验证函数
functionuserCheck(){
varuserName=document.loginForm.username.value;
varpsw=document.loginForm.password.value;
if(userName==""){
window.alert("用户名不能为空");
document.loginForm.username.focus();
returnfalse;
}
else{
varurl="Servlet/userLogin_do";
varparam="userName="+userName+"&psw="+psw;
sendRequestPost(url,param);
}
}
//--></mce:script>
<mce:scripttype="text/javascript"><!--
varxmlHttpRequest;
functioncreateXMLHttpRequest(){
try
{
//Firefox,Opera8.0+,Safari
xmlHttpRequest=newXMLHttpRequest();
}
catch(e)
{
//InternetExplorer
try
{
xmlHttpRequest=newActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttpRequest=newActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("您的浏览器不支持AJAX!");
returnfalse;
}
}
}
}
//发送请求函数
functionsendRequestPost(url,param){
createXMLHttpRequest();
xmlHttpRequest.open("GET",url+"?"+param,true);
xmlHttpRequest.onreadystatechange=processResponse;
}
//处理返回信息函数
functionprocessResponse(){
if(xmlHttpRequest.readyState==4){
if(xmlHttpRequest.status==200){
varres=xmlHttpRequest.responseText;
window.alert(res);
}else{
window.alert("请求页面异常");
}
}
}
//身份验证函数
functionuserCheck(){
varuserName=document.loginForm.username.value;
varpsw=document.loginForm.password.value;
if(userName==""){
window.alert("用户名不能为空");
document.loginForm.username.focus();
returnfalse;
}
else{
varurl="Servlet/userLogin_do";
varparam="userName="+userName+"&psw="+psw;
sendRequestPost(url,param);
}
}
//--></mce:script>

POST
复制代码代码如下:
<mce:scripttype="text/javascript"><!--
varxmlHttpRequest;
functioncreateXMLHttpRequest(){
try
{
//Firefox,Opera8.0+,Safari
xmlHttpRequest=newXMLHttpRequest();
}
catch(e)
{

//InternetExplorer
try
{
xmlHttpRequest=newActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{

try
{
xmlHttpRequest=newActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("您的浏览器不支持AJAX!");
returnfalse;
}
}
}

}
//发送请求函数
functionsendRequestPost(url,param){
createXMLHttpRequest();
xmlHttpRequest.open("POST",url,true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-
urlencoded");
xmlHttpRequest.onreadystatechange=processResponse;
xmlHttpRequest.send(param);
}
//处理返回信息函数
functionprocessResponse(){
if(xmlHttpRequest.readyState==4){
if(xmlHttpRequest.status==200){
varres=xmlHttpRequest.responseText;
window.alert(res);
}else{
window.alert("请求页面异常");
}
}
}
//身份验证函数
functionuserCheck(){
varuserName=document.loginForm.username.value;
varpsw=document.loginForm.password.value;
if(userName==""){
window.alert("用户名不能为空");
document.loginForm.username.focus();
returnfalse;
}
else{
//varurl="Servlet/userLogin_do?userName="+userName+"&psw="+psw;
varurl="Servlet/userLogin_do";
varparam="userName="+userName+"&psw="+psw;
sendRequestPost(url,param);
}
}
//--></mce:script>
<mce:scripttype="text/javascript"><!--
varxmlHttpRequest;
functioncreateXMLHttpRequest(){
try
{
//Firefox,Opera8.0+,Safari
xmlHttpRequest=newXMLHttpRequest();
}
catch(e)
{
//InternetExplorer
try
{
xmlHttpRequest=newActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttpRequest=newActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("您的浏览器不支持AJAX!");
returnfalse;
}
}
}
}
//发送请求函数
functionsendRequestPost(url,param){
createXMLHttpRequest();
xmlHttpRequest.open("POST",url,true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-
form-urlencoded");
xmlHttpRequest.onreadystatechange=processResponse;
xmlHttpRequest.send(param);
}
//处理返回信息函数
functionprocessResponse(){
if(xmlHttpRequest.readyState==4){
if(xmlHttpRequest.status==200){
varres=xmlHttpRequest.responseText;
window.alert(res);
}else{
window.alert("请求页面异常");
}
}
}
//身份验证函数
functionuserCheck(){
varuserName=document.loginForm.username.value;
varpsw=document.loginForm.password.value;
if(userName==""){
window.alert("用户名不能为空");
document.loginForm.username.focus();
returnfalse;
}
else{
//varurl="Servlet/userLogin_do?
userName="+userName+"&psw="+psw;
varurl="Servlet/userLogin_do";
varparam="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");这句代码,不知道为什么,初学,加了就能传递参数了,日后研究。