功能:浏览器中异步发送请求,无刷新获取数据
实现懒加载,提高页面的加载速度
根据用户指定事件部分更新页面
缺点:没有浏览历史,存在跨域问题,seo不友好(爬虫爬不到)
Http协议
发请求:请求报文
请求行:请求方式 url 协议版本
请求头:
请求空行
请求体:get为空,post带内容
响应报文
响应行:版本 响应状态码 响应状态字符串(ok)
响应头
响应空行
响应体:可以返回html代码
express
npm init --yes //初始化
npm i express //安装
ctrl+c 关闭服务
文件右键用terminal打开然后输入node+文件运行服务器
alt shift r :批量替换变量名
xhl中readystate有5个值,初始化是0,1代表open方法执行完毕,2表示send执行完毕,3表示服务端返回的结果,4表示服务端返回所有结果
var button = document.getElementById("getMessage");
var show=document.getElementById("show");
button.onclick=function () {
const xhr=new XMLHttpRequest();
xhr.responseType="json"; //设置response返回数据类型为json,可以直接访问
xhr.open("Get","http://localhost:8000/server");
xhr.send(); //可以发送数据到服务器
xhr.onreadystatechange=function () {
if (xhr.readyState==4){
if (xhr.status>=200&&xhr.status<300){
show.innerHTML=xhr.response.name;
}
else {
}
}
}
}
请求头信息放用户数据校验
ie缓存问题,在路径加date.now传入最新时间
var button = document.getElementById("getMessage");
var show=document.getElementById("show");
var isFirst=true;
var xhl=null;
button.onclick=function () {
if (isFirst==false){
xhr.abort(); //取消请求发送
}else {
xhr=new XMLHttpRequest();
isFirst=false;
xhr.responseType="json";
xhr.open("get","http://localhost:8000/server");
xhr.send();
xhr.onreadystatechange=function () {
if (xhr.readyState==4){
isFirst=true;
if (xhr.status>=200&&xhr.status<300){
show.innerHTML=xhr.response.name;
}
else {
}
}
}
}
}
上面这个防止用户多次发送相同请求导致服务器崩溃
$("#getMessage").click(function () {
$.ajax({
url:"http://localhost:8000/server",
date:{},
type:"get",
dataType:"JSON",
success:function () {},
timeout:1000,
error:function () {},
headers:{}
})
});
axios发送
跨域
同源策略:协议、域名、端口都要一样的安全策略,否则就是跨域
Jsonp实现跨域就是利用script标签的src属性
cors跨域
服务端设置响应头告诉浏览器允许跨域