AJAX POST 与 GET 的区别 && HTTP

来源:互联网 发布:云计算平台storm 编辑:程序博客网 时间:2024/06/04 19:51

一.HTTP (无状态的协议)。

1.HTTP请求过程。

(1)建立TCP连接。

(2)web浏览器向web服务器发送请求命令。

(3)web浏览器发送请求头信息。

(4)web服务器应答。

(5)web服务器发送应答头信息。

(6)web服务器向浏览器发送数据。

(7)web服务器关闭TCP连接。


一个HTTP请求一般有四部分组成:

(1)HTTP请求的方法或动作,比如get还是post请求。

(2)正在请求的URL。总的知道请求的地址是什么。

(3)请求头。包含一些客户端环境信息,身份验证信息等。

(4)请求体。也就是请求正文。包含客户提交的查询字符串信息,表单信息等。

一般请求头与请求体会有空行。代表请求头结束,接下来的是请求体。


GET:一般用于信息获取,默认请求方法。一般是安全的,主要用于查询。发送的信息对任何人都是可见的,所有的变量名和值都显示在URL里。也就是用URL 传递参数。所以 get请求发送的数量也有限制。大约2000 个字符。(幂等:查询一次 == 一万次 )

POST:一般用于修改服务器的上的资源。一般存表单,发数据。 都会嵌入HTTP请求体中。也没有数量的限制。

GET && Post  区别 :

1.GET 访问浏览器 认为 是幂等的.就是 一个相同的URL只有一个结果(相同是指:整个URL 字符串完全匹配),所以第二次访问的时候,如果URL字符串没有变化,浏览器是直接拿出第一次的结果的. 所以 查询一次 == 一万次 .

 POST 则认为是一个变动性访问.(浏览器认为POST的提交必定是有改变的.)

为了防止GET的等幂访问, 就在 URL 后面加上 ?+new Date();  因为,data 每次都会更新,到时url 的字符串 有改变,这样就能保证,url 不会取缓存里面的东西了. 当然也可以 添加参数 .

 eg: url+"?id="+1+"&name="+"hello" + "&time="+ new Date().getTime();

解释:

?: 问号代表URL地址的结尾与数据参数的开端

后面的参数每一个数据参数以“名称=值”的形式出现.参数与参数之间利用一个连接符&来区分

+ : 必须用+ 连接数据 / 变量. 

使用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"];

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');



下面属于转载部分::

http://www.nowamagic.net/librarys/veda/detail/1244

Get 与 Post 的区别

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">是不一样的。
当我们在提交表单的时候我们通常用post方式,当我们要传送一个较大的数据文件时,需要用post。当传递的值只需用参数方式(这个值不大于2KB)的时候,用get方式即可。

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

GET 方式,浏览器键入 http://localhost?username=张三


1GET /?username=%E5%BC%A0%E4%B8%89 HTTP/1.1
2Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*
3Accept-Language: zh-cn
4Accept-Encoding: gzip, deflate
5User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)
6Host: localhost
7Connection: Keep-Alive

POST 方式:


01POST / HTTP/1.1
02Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*
03Accept-Language: zh-cn
04Content-Type: application/x-www-form-urlencoded
05Accept-Encoding: gzip, deflate
06User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)
07Host: localhost
08Content-Length: 28
09Connection: Keep-Alive
10username=%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 方式


1varpostContent ="name="+ encodeURIComponent("xiaocheng") +"&email="
2    + encodeURIComponent("xiaochengf_21@yahoo.com.cn");
3xmlhttp.open("GET","somepage"+"?" + postContent,true);
4xmlhttp.send(null);

POST 方式


1varpostContent ="name="+ encodeURIComponent("xiaocheng") +"&email="
2    + encodeURIComponent("xiaochengf_21@yahoo.com.cn");
3xmlhttp.open("POST","somepage",true);
4xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
5//xmlhttp.setRequestHeader("Content-Type", "text/xml"); //如果发送的是一个xml文件
6xmlhttp.send(postContent);

get方式

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

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


1<bodystyle="text-align: center">
2    <inputtype="text"id="txt"/>
3    <br/>
4    <inputtype="button"value="get方式回调" onclick="get()"/>
5</body>

js代码文件


01varxhr=getXHR();//获得xmlhttprequest对象,getXHR函数的具体实现这里不给出,因为非常简单
02functionget()
03{
04    varstr=document.getElementById ("txt").value;
05    varurl="PageAjax.aspx?argument="+escape(str);//编码str
06    xhr.open("get",url,true);
07    xhr.onreadystatechange=renew;
08    xhr.send(null);//不发送任何内容,因为url中包含了参数数据
09}
10functionrenew()
11{
12    if(xhr.readystate==4)
13    {
14        if(xhr.status==200)
15        {
16            varresponse=xhr.responsetext;
17            varres=response.split('\n');
18            alert(res[0]);
19        }
20    }
21}

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


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

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

post方式

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

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


1<textareaid="TextArea1"style="width: 323px; height: 76px"></textarea>
2    <br/>
3    <inputid="Button1"type="button"value="post方式回调"onclick="post()"/>

js代码文件


01varxhr=getXHR();//获得xmlhttprequest对象,getXHR函数的具体实现这里不给出,因为非常简单
02functionpost()
03{
04    varstr=document.getElementById ("TextArea1").value;
05    varpoststr="arg="+str;
06    varurl="PageAjax.aspx?time="+newDate();//加一时间戳,放置发回的数据是服务器缓存的数据
07    xhr.open("post",url,true);
08    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//告诉服务器发送的是文本
09    //xhr.setRequestHeader("Content-Type", "text/xml"); //告诉服务器发送的是一个xml文件
10    xhr.onreadystatechange=update;
11    xhr.send(poststr);//发送poststr数据到服务器
12}
13functionupdate()
14{
15    if(xhr.readystate==4)
16    {
17        if(xhr.status==200)
18        {
19            varresponse=xhr.responsetext;
20            varres=response.split('\n');
21            alert(res[0]);
22        }
23    }
24}

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


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

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

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


01....... 
02functioncreateQueryString(){ 
03 varfirstName = document.getElementById("firstName").value; 
04 varsecName = document.getElementById("secName").value; 
05   
06 varquerystring="firstName="+firstName+"&secName="+secName; 
07
08   
09   
10//GET方式 
11functiondoRequestUsingGET(){ 
12   createXMLHttpRequest(); 
13   varqueryString ="test.php?"
14   queryString= queryString + createQueryString()+"&timstamp="+newDate().getTime(); 
15   Ajax.onreadystatechange=handleStateChange; 
16   Ajax.open("GET",queryString,true); 
17   Ajax.send(null); 
18   
19
20   
21//POST方式 
22functiondoRequestUsingPOST(){ 
23   createXMLHttpRequest(); 
24   
25  /* 注意以下代码与GET方式的区别 */ 
26   varurl="test.php?timstamp="+newDate().getTime(); 
27   // POST 需要定义发送的字符串
28   varqueryString=createQueryString();
29   Ajax.open("POST",url,true); 
30   Ajax.onreadystatechange=handleStateChange; 
31   // POST 需要设置请求头部
32   Ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded"
33   // 参数不为 null
34   Ajax.send(queryString); 
35   
36
37   
38functionhandleStateChange(){ 
39    if(Ajax.readyState==4){ 
40       if(Ajax.status==200){ .......}  //成功数据其它数据 
41    
42   



0 0
原创粉丝点击