原生ajax请求
发送
get请求btn.onclick=function(){
var xhr=new XHLHttpRequerst();
xhr.open("GET",'./be/txt',false);
xhr.onreadystatechange=function(){
if(xhr.status==200&&xhr.readyState==4){
content.innerHTML=xhr.responseText;
}
}
xhr.send();
}
post请求
btn.onclick=function(){
var xhr=new XHLHttpRequerst();
var name=document.getElementById("name").value;
var age=document.getElementById("age").value;
xhr.open("POST",'./be/txt',false);
xhr.onreadystatechange=function(){
if(xhr.status==200&&xhr.readyState==4){
content.innerHTML=xhr.responseText;
}
}
xhr.send('name=${name}&age=${age}');
}
浏览器的同源策略
相同地址可以相互访问,负责就需要跨域
同源要求协议一样地址一样端口一致
jquery中的ajax三层
- 上层
$.getJSON()
$(function(){
$("button").click(function(){
$.getJSON("./be.json",function(data,status,xhr){//检一个be.json data 内容 status 成功不成功 xhr
console.log(data,status,xhr);
$("p").text(JSON.stringify(data));
})
})
})
$.getscript()
$(function(){
$("button").click(function(){
$.getScript("./script.js")
})
})
$load()
$(function(){
$("button").click(function(){
$("p").load("./be.html p")//调用be.html 的p
})
})
- 中层
$(function(){
$("button").click(function(){
$.get("./be.txt",function(data,status,xhr){
if(status=="success"){
$("p").text(data);
}
})
})
})-
$(function(){
$("button").click(function(){
$.get("./be.txt")
.done(res=>{//成功
$("p").text(res);
})
.fail(err=>{//失败
console.log(err)
})
.always(xhr=>{//无论失败还是成功都执行
console.log("成功失败都执行",xhr)
})
})
})
get请求
$(function(){
$("button").click(function(){
$.get("./be.txt")
.then(res=>{//成功
$("p").text(res);
})
.catch(err=>{//失败
console.log(err)
})
})
})
post请求
$(function(){
$("button").click(function(){
var name=$("#name").val();
var age=$("#age").val();
var data={name,age};
$.post("http://www.520mg.com/ajax/echo.php",data)
.then(res=>{
$("p").text(res);
})
.catch(res=>{
console.log(err)
})
})
})
HTTTP网络状态码
- 200:成功,一切正常
- 301:永久转移(永久重定向)一般来说做域名的转移的时候会用到
- 302:临时转移(临时重定向)服务器负载均衡
- 304:读取的是缓存中的数据
- 307:临时重定向
- 400:请求参数错误
- 401:请求权限不够
- 404:请求地址不存在
- 500:未知的服务器错误
- 503:服务器超负荷请求
- 504:响应超时,可能是服务器端未打开()