Ajax:异步js和xml
异步刷新
如果网页中某一个地方需要修改,异步刷新可以使:只刷新该需要修改的地方,而页面中其他地方保持不变,例如百度搜索框、视频点赞
实现
js:XMLHttpRequest对象
XMLHttpRequest对象的方法:
- open(方法名(提交get|post),服务器地址,true):与服务器建立连接
- send():
- get:send(null)
- post:send(参数值)
- setRequestHealther(header,value):
- get:不需要设置此方法
- post:需要设置
- 如果请求元素中包含了文件上传:setRequestHeader(“Content-Type”,“multipart/form-data”)
- 不包含文件上传:setRequestHeader(“Content-Type”,“application/x-www-form-urlencoded”)
XMLHttpRequest对象的属性:
- readystate:请求状态(只有状态为4时代表请求完毕)
- state:响应状态(只有200代表响应正常)
- onreadystatechange:回调函数
- responseText:响应格式为String
- responseXML:响应格式为XML
代码示例:
Post方式
window.onload=function(){
document.getElementById("ok").onclick=function(){
var xhr=createXmlHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4)
{
if(xhr.status==200 || xhr.status==304)
{
var data=xhr.responseText;
alert(data);
}
}
};
xhr.open("post","../testGetServelet",true);
//如果是POST请求方式,设置请求首部信息
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("a=1&b=2");
};
function createXmlHttpRequest(){
var xmlHttp;
try{
//Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}catch (e){
try{
//Internet Explorer
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
}
}
}
return xmlHttp;
}
};
代码示例:
Get方式
window.onload=function()
{
document.getElementById("ok").onclick=function(){
var xhr=createXmlHttpRequest();//获取XmlHttpRequest对象
xhr.onreadystatechange=