Ajax中Get请求与Post请求的区别

Get请求和Post请求的区别:

1、使用get请求时,参数在url中可见;而使用post不可见,自带加密
2、使用get发送请求的数据量比较小;使用post请求数据量比较大;

get请求的js代码:
function click() {
    var xmlHttp = window.XMLHttpRequest ? 
        new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    var username = document.getElementById("username").value;
    var 
userpassword
= document.getElementById("userpassword").value;

//添加参数,以求每次访问不同的url,以避免缓存问题 
xmlHttp.open("get", "Server.aspx?username=" + encodeURIComponent(username) + "&
userpassword
=" + encodeURIComponent(age) + "&random=" + Math.random());

xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { document.getElementById("result").innerHTML = xmlHttp.responseText; } }


 //发送请求,参数为null xmlHttp.send(null);}

post请求:


function click() {
    var xmlHttp = window.XMLHttpRequest ?
        new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    var username = document.getElementById("txt_username").value;
    var 
password
= document.getElementById("password").value;

var data = "username=" + encodeURIComponent(username) + "&
password
=" + encodeURIComponent(

password


);

//不用担心缓存问题 xmlHttp.open("post", "Server.aspx", true); //必须设置,否则服务器端收不到参数






xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { document.getElementById("result").innerHTML = xmlHttp.responseText; } } 





//发送请求,要data数据 xmlHttp.send(data);}

区别:

1.get请求需注意缓存问题,post请求不需担心这个问题;

2.post请求必须设置Content-Type值为application/x-form-www-urlencoded;

3.发送请求时,因为get请求的参数都在url里,所以send函数发送的参数为null,而post请求在使用send方法时,却需赋予其参数;

何时使用Get请求,何时使用Post请求

Get请求的目的是给予服务器一些参数,以便从服务器获取列表.例如:list.aspx?page=1,表示获取第一页的数据

Post请求的目的是向服务器发送一些参数,例如form中的内容.



















Ajax请求的步骤:
1、创建一个XMLHttpRequest对象:
var request=new xmlHttpRequest();
2、设置请求参数:
request.open(‘get’,"请求的地址",true)
3、设置回调函数:





request.onreadstatechange=function(){





	if(request.readystate==4&&request.status==200){





	var str=request.responseText;





	if(str=='1'){





	$('id').innerHTML=""		





	}		





	}










}













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值