ajax的get和post区别,AJAX使用get与post模式的区别分析

本文实例分析了AJAX使用get与post模式的区别。分享给大家供大家参考。具体分析如下:

如果是get 模式的请求,则将传递参数通过URL 地址发送到服务器端;

如果是post 模式的请求,则将传递参数通过send( ) 方法发送到服务器端(并且必须设置请求文件头);

post 模式的代码如下:

一个演示get 模式与post 模式区别的示例:

客户端:

代码示例:

GET VS. POST

var xmlHttp;

function createXMLHttpRequest(){

if(window.ActiveXObject)

xmlHttp = new ActiveXObject("Microsoft.XMLHttp");

else if(window.XMLHttpRequest)

xmlHttp = new XMLHttpRequest();

}

function createQueryString(){

var firstName = document.getElementById("firstName").value;

var birthday = document.getElementById("birthday").value;

var queryString = "firstName=" + firstName + "&birthday=" + birthday;

return encodeURI(encodeURI(queryString)); //两次编码解决中文乱码问题

}

// GET 模式

function doRequestUsingGET(){

createXMLHttpRequest();

var queryString = "9-3.aspx?";

queryString += createQueryString() + "&timestamp=" + new Date().getTime();

xmlHttp.onreadystatechange = handleStateChange;

xmlHttp.open("GET",queryString);

xmlHttp.send(null);

}

// POST 模式

function doRequestUsingPOST(){

createXMLHttpRequest();

var url = "9-3.aspx?timestamp=" + new Date().getTime();

var queryString = createQueryString();

xmlHttp.open("POST",url);

xmlHttp.onreadystatechange = handleStateChange;

xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

xmlHttp.send(queryString);

}

function handleStateChange(){

if(xmlHttp.readyState == 4 && xmlHttp.status == 200){

var responseDiv = document.getElementById("serverResponse");

responseDiv.innerHTML = decodeURI(xmlHttp.responseText);//解码

}

}

输入姓名和生日

服务器端

代码示例:

if(Request.HttpMethod == "POST")

Response.Write("POST: " + Request["firstName"] + ", your birthday is " + Request["birthday"]);

else if(Request.HttpMethod == "GET")

Response.Write("GET: " + Request["firstName"] + ", your birthday is " + Request["birthday"]);

%>

通常在数据不多,并且不敏感的时候,使用get 模式的请求;

而数据量大,或者数据敏感的时候,使用post 模式的请求。

希望本文所述对大家的Ajax程序设计有所帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值