您的位置:首页 > 其它

Ajax中Get和Post的区别

2009-09-11 16:52 429 查看
谈Ajax的Get

和Post

的区别


Get

方式:

用get

方式可传送简单数据,但大小一般限制在1KB下,数据追加到url中发送(http的header传送),也就是说,浏览器将

各个表单字段元素及其数据按照URL参数的格式附加在请求行中的资源路径后面。另外最重要的一点是,它会被客户端的浏

览器缓存起来,那么,别人就可以从浏览器的历史记录中,读取到此客户的数据,比如帐号和密码等。因此,在某些情况

下,get

方法会带来严重的安全性问题。

实例:

//GET提交
var postContent =
"name=" + encodeURIComponent("Buford Early") + "&email=" + encodeURIComponent("buford@known-space.com");
//参数附在URL后面
var url = "www,baidu.com";
xmlhttp.open("GET", url + "?" + postContent, true);
xmlhttp.send(null);


Post

方式:

当使用POST

方式时,浏览器把各表单字段元素及其数据作为HTTP消息的实体内容发送给Web服务器,而不是作为URL地址的

参数进行传递,使用POST

方式传递的数据量要比使用GET

方式传送的数据量大的多。

实例:

//POST提交
var postContent =
"name=" + encodeURIComponent("Buford Early") + "&email=" + encodeURIComponent("buford@known-space.com");
var url = "www.baidu.com";
xmlhttp.open("POST", "somepage", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//表单信息在send中发送
xmlhttp.send(postContent);


总之,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"];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: