AJAX
Ajax技术核心是XMLHttpRequest对象(简称XHR)
IE7+、Firefox、Opera、Chrome和Safari都支持原生的XHR对象,在这些浏览器中创建XHR对象可以直接实例化XMLHttpRequest即可。
var xhr = new XMLHttpRequest();
alert(xhr);
与服务器通信的API就是XMLHttpRequest
都需要那些步骤来通信呢,简单理解一共只有4步
1、新建XMLHttpRequest对象
var request=new XMLHttpRequest();
IE 7以下 var request=new ActiveXObject("Microsoft.XMLHTTP");
2、打开要发送的地址通道。
request.open(“GET”,地址,同步/异步);
3、给XMLHttpRequest对象增加侦听器,用来侦听各种情况,包括各种链接状态
request.addEventListener(“load”,侦听函数)发送数据给打开的地址
4、如果没有要发送的内容直接send()
request.send();
数据提交给服务器有两种方式:
第一种:
表单提交,通过表单submit触发,提交到form中action属性地址,使用的方法是methed给出
这种方式有个缺陷,需要跳转页面
第二种:
通过ajax提交的,就不能触发submit,而是通过按钮点击,直接使用ajax发送给服务端
发送到的地址就是open中的第二个参数,发送方法就是open的第一个参数
不需要跳转页面,缺陷,部分内容无法进行SEO优化
以上情况只能二选一
GET和POST请求方式
GET:通过地址栏后面 ? 带入字符串,字符串格式是变量=值&变量=值的方式传递数据给服务器
这种传送方式仅仅是去服务端获取,没有单独传递数据,并且从服务端获取需要内容,这个就是GET
传递给服务器的数据少,而且是明文传递,只能使用字符串,并且数据无法进行多样性嵌套
如果地址是当前页面锚点是可以提交页面
POST:数据不是通过地址栏发送,通过数据握手后信道发送数据,并且会将数据转换为二进制数据发送给服务器
传送数据可以是任意复杂度数据,但是传送的数据类型,包含了字符串,二进制流其它一些格式
如果使用GET方式发送,数据会写在url后面?后面的内容
如果使用POST方法发送,数据会被写在send中
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("POST","http://localhost:4010/a.php");
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
xhr.send("user=张三");
function loadHandler(e){
console.log(this.response);
}
1\表单提交还是ajax发送,表单不需要跨域, ajax需要考虑跨域
2\使用GET还是使用POST,数据发送的形式不同,一个是地址后缀,一个是send发送
3\如果使用POST,是发送给NodeJs还是发送给PHP ,服务器语言不同,处理方式不同
4\AJAX--->POST--->PHP 需要写请求头xhr.setRequestHeader
如果访问node直接访问域名端口号
如果访问php,jsp,一般带有文件名
请求本地数据 AJAX不单纯可以请求服务器数据,还可以请求本地数据
加载本地文件
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("GET","./a.text");
xhr.send();
function loadHandler(e){
var div=document.querySelector("div");
div.textContent=this.response;
}
加载外部的json文件,注意只能读取,不能写入
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("GET","./config.json");
xhr.send();
function loadHandler(e){
var obj=JSON.parse(this.response);
console.log(obj.backgroundColor);
document.documentElement.style.backgroundColor=obj.backgroundColor;
}
加载外部XML文件
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("GET","./a.xml");
xhr.send();
function loadHandler(e){
xml=xhr.responseXML;
var na=xml.querySelectorAll("NA>man")[0];
console.log(na.getAttribute("name"));
}
加载图片
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("GET","./img/2.jpg");
xhr.send();
function loadHandler(e){
console.log(this.response);
}
加载html
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("GET","./a.html");
xhr.send();
function loadHandler(e){
var div=document.querySelector("div");
div.innerHTML=this.response;
}
同步和异步
异步
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("POST","http://localhost:4010/a.php");
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send("user=zhangsan");
console.log("a");
function loadHandler(e){
console.log(this.response);
console.log("b");
}
console.log("c");
阻塞式同步
var xhr=new XMLHttpRequest();
xhr.open("POST","http://localhost:4010/a.php",false);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send("user=weizheng");
console.log("a");
console.log(xhr.response);
console.log("c");
请求消息:客户端发送给服务端的消息
响应消息:服务端发送给客户端的消息
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("POST","http://localhost:4010/a.php");
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.setRequestHeader("names","zhangsan");
xhr.send("user=zhangsan");
function loadHandler(e){
console.log(this.response);
}
在客户端中可以设置请求头和获取响应头
在服务端中可以获取请求头和设置响应头
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("POST","http://localhost:8000");
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.setRequestHeader("dataType","json");
xhr.send("user=zhangsan");
function loadHandler(e){
console.log(xhr.getAllResponseHeaders());
console.log(xhr.getResponseHeader("content-type"));
}
send()发送
发送JSON字符串
var obj={
user:"weizheng",
age:21
}
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("POST","http://localhost:8000");
xhr.send(JSON.stringify(obj));
function loadHandler(e){
}
上传Blob(二进制)数据,比如图片文件等
var form=document.querySelector("form");
form.addEventListener("submit",submitHandler);
function submitHandler(e){
e.preventDefault();
var file=document.querySelector("[type=file]");
var xhr=new XMLHttpRequest();
xhr.open("POST","http://localhost:8000");
xhr.addEventListener("load",loadHandler);
xhr.send(file.files[0]);
var xhr=new XMLHttpRequest();
xhr.open("POST","http://localhost:8000");
xhr.addEventListener("load",loadHandler);
xhr.send(file.files[1]);
var xhr=new XMLHttpRequest();
xhr.open("POST","http://localhost:8000");
xhr.addEventListener("load",loadHandler);
xhr.send(file.files[2]);
}
function loadHandler(e){
console.log(this.response);
}
直接发送document或者可以直接将HTML发送给服务器
var x=new XMLHttpRequest();
x.addEventListener("load",xmlLoadHandler);
x.open("GET","./a.xml");
x.send();
function xmlLoadHandler(e){
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("POST","http://localhost:8000");
xhr.send(x.responseXML);
}
function loadHandler(e){
}
formData 发送表单数据
var form=document.querySelector("form");
form.addEventListener("submit",submitHandler);
function submitHandler(e){
e.preventDefault();
var fd=new FormData(form);
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("POST","http://localhost:8000");
xhr.send(fd);
}
function loadHandler(e){
}
timeout 超时,因为各种因素导致数据前后端传递的延迟
设置时间等待,如果超过这个时间,就切断数据发送
var xhr=new XMLHttpRequest();
xhr.open("POST","http://localhost:8000");
xhr.addEventListener("load",loadHandler);
xhr.addEventListener("timeout",tiemOutHandler);
xhr.timeout=2000;
xhr.send("超时等待");
function loadHandler(e){
}
function tiemOutHandler(e){
xhr.abort();
}
readystate
var xhr=new XMLHttpRequest();
xhr.addEventListener("readystatechange",readyStateHandler);
xhr.open("POST","http://localhost:8000");
xhr.send("aaa");
值 状态 描述
0 UNSENT 代理被创建,但尚未调用open()方法
1 OPENED open()方法已经被调用
2 HEADERS_RECEIVED send()方法已经被调用,并且头部和状态已经可获得
3 LOADING 下载中;responseText()属性已经包部分数据
4 DONE 下载操作已完成
当一个文档的 readyState 属性发生更改时,readystatechange 事件会被触发。
状态主要分
1、信息 100-101
2、成功 200-206
3、重定向 300-307
4、客户端错误 400-417
5、服务器错误 500-505
function readyStateHandler(e){
console.log(this.readyState,this.status);
if(this.readyState===4 && this.status===200){
console.log(this.response);
}
}
获取表单内容,在页面显示
发送数据给服务端,接受服务端返回过来的数据(GET发送方式)
css样式
#div0{
width: 100px;
height: 100px;
position: absolute;
right: 0;
top: 0;
font-size: 30px;
}
<form action="http://localhost:4010" method="GET">
<label>user</label>
<input type="text" name="user"><br>
<label>password</label>
<input type="password" name="password"><br>
<label>x</label>
<input type="text" name="x"><br>
<label>y</label>
<input type="text" name="y"><br>
<button type="submit">提交</button>
</form>
<div id="div0"></div>
var form=document.querySelector("form");
var inputs=document.querySelectorAll("input");
form.addEventListener("submit",submitHandler);
function submitHandler(e){
e.preventDefault();
var user=inputs[0].value;
var password=inputs[1].value;
var x=inputs[2].value;
var y=inputs[3].value;
var url="http://localhost:4010?user="+user+"&password="+password+"&x="+x+"&y="+y;
ajax(url);
}
function ajax(url){
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("GET",url);
xhr.send();
}
function loadHandler(e){
console.log(this.response);
var div0=document.getElementById("div0");
div0.textContent=this.response;
}
处理客户端请求的内容,再将内容发送给客户端
var http=require("http");
var query=require("querystring");
var server=http.createServer(function(req,res){
req.on("data",function(){
});
req.on("end",function(){
var str=req.url.split("?")[1];
var obj=query.parse(str);
var sum=Number(obj.x)+Number(obj.y);
res.writeHead(200,{
"content-type":"text/html;charset=utf-8",
"Access-Control-Allow-Origin":"*"
})
res.write(sum.toString());
res.end();
});
})
server.listen(4010,"localhost",function(){
console.log("开启了服务");
})
发送数据给服务端,接受服务端返回过来的数据(POST发送方式)
css样式
#div0{
width: 100px;
height: 100px;
position: absolute;
right: 0;
top: 0;
font-size: 30px;
}
<form action="http://localhost:4010" method="GET">
<label>user</label>
<input type="text" name="user"><br>
<label>password</label>
<input type="password" name="password"><br>
<label>x</label>
<input type="text" name="x"><br>
<label>y</label>
<input type="text" name="y"><br>
<button type="submit">提交</button>
</form>
<div id="div0"></div>
var form=document.querySelector("form");
var inputs=document.querySelectorAll("input");
form.addEventListener("submit",submitHandler);
function submitHandler(e){
e.preventDefault();
var user=inputs[0].value;
var password=inputs[1].value;
var x=inputs[2].value;
var y=inputs[3].value;
var str="user="+user+"&password="+password+"&x="+x+"&y="+y;
ajax(str);
}
function ajax(str){
var xhr=new XMLHttpRequest();
xhr.addEventListener("load",loadHandler);
xhr.open("POST","http://localhost:4010");
xhr.send(str);
}
function loadHandler(e){
console.log(this.response);
var div0=document.getElementById("div0");
div0.textContent=this.response;
}
处理客户端请求的内容,再将内容发送给客户端
var http=require("http");
var query=require("querystring");
var server=http.createServer(function(req,res){
var str="";
req.on("data",function(_data){
str=_data.toString();
});
req.on("end",function(){
var obj=query.parse(str);
var sum=Number(obj.x)+Number(obj.y);
res.writeHead(200,{
"content-type":"text/html;charset=utf-8",
"Access-Control-Allow-Origin":"*"
})
res.write(sum.toString());
res.end();
})
})
server.listen(4010,"localhost",function(){
console.log("开启了服务");
})