1.用XMLHttpRequest对象的ajax请求
post和get在向后台传值上有所不同
////////GET请求////////
$(function(){
$("#btnGet").click(function(){
var xhr;
if(XMLHttpRequest){ //高版本IE 或者其他浏览器创建对象
xhr=new XMLHttpRequest();
} else{
xhr=new ActiveXobject("Microsoft.XMLHTTP");//低版本IE
}
xhr.open("get","GetDate.ashx?name=123",true);//第二个参数是要请求的处理程序
xhr.send();//开始发送
//回调函数:当服务器返回数据给浏览器后,自动调用该方法
xhr.onreadystatechange=function(){
if(xhr.readyState==4){//服务端返回数据,数据完整
if(xhr,status==200){//判断响应状态码是否为200
*******
}
}
}
});
});
//////POST请求///////
在传值上与get请求不同
$(function(){
$("#btnPost").click(function(){
var xhr;
if(XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXobject("Microsoft.XMLHTTP")
}
xhr.open("psot","GetDate.ashx",true);
xhr.send("name=zhangsan&pwd=123");//向后台传的参数放在此处
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
}
}
}
});
});
2.jquery下的ajax请求
(1)GET请求和Post请求分开写的写法
//GET请求
$(function(){
$("#btnGet").click(function(){
$.get("GetDate.ashx",{"name":"Lucy","pwd","123"}),function(data){
alert(data)
});
});
});
//POST请求
$(function(){
$("#btnPost").click(function(){
$.post("GetDate.ashx",{"name":"Lucy","pwd","123"},function(data){
alert(data)
});
});
});
(2)通用写法
type包含GET和POST,url是要请求的处理程序或者控制器,data是要向后台传递的参数
$(function(){
$("#btnAja").click(function(){
$.ajax({
type:"post",
url:"some.php",
data:"name=Lucy&pwd=123"
success:function(msg){
alert("Data Saved:"+msg);
}
});
});
});