AJAX全称为Asynchronous Javascript And XML (异步的JS和XML)。通过AJAX可以在浏览器中发送异步请求,最大的优势是不用刷新就能获取数据。
优点:
缺点:
XML可扩展标记语言,用来传输和存储数据。XML和HTML类似,但HTML中是预定于标签,而XML都是自定义标签。现在已经被JSON取代了。
跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器施加的安全限制。
所谓同源是指,域名,协议,端口均相同,只要有一个不同,就是跨域。localhost和127.0.0.1虽然都指向本机,但也属于跨域。
跨域会阻止接口的请求,会阻止Dom的操作。
HTTP(hypetext transport protovol)协议,超文本传输协议,规定了浏览器与万维网服务器之间互相通信的规则。
请求报文
响应报文
下载node.js 和express:操作链接
//获取元素
const btn=document.getElementByTagName('button')[0];
//绑定事件
btn.onclick=function(){
//1.创建对象
const xhr=new XMLHttpRequest();
//2.初始化 设置请求方法和url
xhr.open('GET','http://127.0.0.1:8000/路径');
//3.发送
xhr.send();
//4.事件绑定 处理服务器端返回结果
//readystate 是xhr对象中的属性,表示状态0 1 2 3 4
//0 未初始化 1 open调用完毕 2 send调用完毕 3 服务器返回部分结果 4 返回所有结果
xhr.onreadystatechange=function(){
if(xhr.readystate===4){
if(xhr.status>=200&&xhr.status<300){
result.innerHTML=xhr.response;
}
}
}
}
在url中之间设置。
xhr.open('POST','http://127.0.0.1:8000/路径+参数');
//设置请求头
xhr.setRequestHeader('type','content');
//设置请求体
xhr.send('请求体');
服务器端发送:
const data={name:'hh'};
let str=JSON.stringify(data);
response.send(str);
客户端接收:
//手动转换
let data=JSON.parse(xhr.response);
console.log(data.name);
//自动转换
console.log(xhr.response.name);
//1. 2s内未收到结果就取消
xhr.timeout=2000;
//2. 设置超时回调,超时后调用该函数
xhr.ontimeout=function(){}
//网络异常回调
xhr.onerror=function(){}
xhr.abort();
//标识是否正在发送ajax请求
let isSending=false;
//发送后将isSending 改为true
//绑定事件
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
isSending=false;
}
}
fetch('url',{
method:'POST',
//请求头
headers:{
name:'ahh'
},
//请求体
body:''
}).then(response=>{
return response.text();//response.json();
});
$.get(url,[data],[callback],[type])
$.post(url,[data],[callback],[type])
$('button').eq(0).click(function(){
$.ajax({
url:'',
data:{a:100,b:200},
type:'GET' //'POST',
dataType:'json',
success:function(data){},
timeout:2000,
error:function(){}
})
})
浏览器的一种安全策略,同源:协议、域名、端口号必须完全相同。
违背同源策略就是跨域。
有些标签具有跨域能力,img、link、iframe、script,JSONP就是使用script标签的跨域能力来发送请求的。
script发送请求应该返回js语句。
jQuery发送jsonp请求:
$('button').eq(0).click(function(){
$.getJSON('url',function(data){})
})
不需要在客户端做任何特殊操作,完全在服务器中进行处理,支持get和post请求。
CORS通过设置一个响应头来告诉浏览器,该请求允许跨域。
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Header","*");
response.setHeader("Access-Control-Allow-Method","*");
//*:全部
// 也可以写一个具体的url地址。