ajax:异步传输=js+xml
异步刷新:网页中只有某一块需要修改,不影响其他块。比如说弹幕,点赞等!
实现:
js:
XMLHttpRequest 对象;
该对象的方法:
open( 提交方式,服务器地址 ,true):与服务器建立连接
send(): ①get请求:send(nulll); ②post请求:send(参数值);
setRequestHeader(header,value): get:不需要设置; post:需要设置:①包含文件上传:setRequestHeader(“Content-Type”,“multiparty/form-data”); ②不包含文件:setRequestHeader(“Content-Type”,“application/x-www-form-urlencoded”);
该对象的属性:
readyState: 请求状态,等级0-4,值越大越完整,4代表ok
status: 响应状态。响应状态码,200=ok;400=无法找到服务资源;403=没有访问权限;404=访问资源不存在;500=服务器内部错误,很有可能是内部程序有错。
onreadystatechange: 回调函数
responseText: 响应格式为string
responseXML: 响应格式为xml
实例:
function aa(){
//id=stuentId,请求服务端
xmlHttpRequest=new XMLHttpRequest();
//设置回调函数
xmlHttpRequest.onreadystatechange=callBack;
xmlHttpRequest.open("post","StudentServlet",true);
//设置post方式的头信息
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//如果是get传递的值直接拼接在后面。
xmlHttpRequest.send("stuentId="+stuentId)//k=v
}
//接收服务器的返回值
function callBack(){
if(xmlHttpRequest.readyState==4&&xmlHttpRequest.status==200){
//接收格式
var data=xmlHttpRequest.responseText;
if(data=="true"){
alert("已存在");
}else{
alert("不存在");
}
}
}
jquery:
导入jquery的包。
举例方式:
①
$.ajax({
url:服务器地址,
请求方式:post
data:请求数据
success:function(result,testStatus){
},
error:function(xmr,errorMessage,e){
}
})
②
$.get(
服务器地址,
请求数据
function(result){
},
预期值返回类型(string/xml)//常见返回值:"xml","json","text"
)
③
$.post(
服务器地址,
请求数据
function(result){
},
预期值返回类型(string/xml)
)
实例:
function aa(){
//id=stuentId,请求服务端
var student=$("#stuentId").val();//jquery拿值方式
$.ajax({
url:“StudentServlet”,
请求方式:“post”
data:"stuentId="+stuentId,
success:function(result,testStatus){
if(result=="true"){
alert("已存在,失败");
}
else{
alert("不存在,成功");
}
},
error:function(xmr,errorMessage,e){
alert("系统异常");
}
})
}
$.get(
“StudentServlet”,
"stuentId="+stuentId,
function(result){
if(result=="true"){
alert("已存在,失败");
}else{
alert("不存在,成功");
}
},
},
//常见返回值:"xml","json","text"
"text"
)
//一般用load连function都省略掉。
$("#id").load(
“StudentServlet”,
"stuentId="+stuentId,
function(result){
if(result=="true"){
alert("已存在,失败");
}else{
alert("不存在,成功");
}
}
)
//json方式,通过key拿value.
举例:
var student = {"name":"zhouyi","age":"25"};//如果是json数组,是中括号[ ]
alert(student.name+"--"+student.age);//结果是zhouyi--25,字符串的拼接用双引号。
实例:
//返回的是json形式的数据,所以返回的数据需要转换或者都已json处理。这里举例都以json处理。
function testJson(){
$.getJson(
“StudentServlet”,
//"stuentId="+stuentId,
{"name":"zhouyi","age":"25"},
function(result){
var jsonStudent = eval(result);//通过eval()函数,将返回值转为一个js能够识别的json对象。
$.each(jsonStudent ,function(){
alert(this.name+"--"+this.age)
})
}
)
}