HTTP
htttp一种无状态的网络协议
http的请求过程
1.建立tcp网络连接(与服务器联通)
2.客户端发送请求头+请求体
3.服务器应答响应头+响应体
4.关闭TCP连接
5.客户端(浏览器)渲染内容
请求头的组成
请求标头 (查看解析结果)
请求头(请求报头)
响应式的组成
响应行
HTTP/1.1协议
200响应码
ok状态
响应头信息
Content-Type返回的数据类型
空行
请求的方法
响应码
XMLHTTPRequst(xhr)
get请求
post请求
JQuery中的ajax
.load方法
语法
el.load(url)
解释
把url的内容通过ajax加载到el内部
示列
$.get()方法
通过get请求方式,获取内容
语法
$.get(url)
.then(res=>res)
.catch(xhr=.xhr)
.then的前面一行没有分号结尾
示列
向服务器请求一条笑话信息
$.get("http://520mg.com/mi/list.php?page=1")
.then(res=>{
//res即时服务器返回的内容
//.then方法就是请求成功后获取的内容的方法
})
.catch(xhr=>{
//.catch就是请求失败(通常是网络错误)响应方法
//xhr 就是jquery封装的XMLHttpRequest对象
})
$.post()方法
以post方法向服务器发起请求
语法
$.post(url,data)
.then(res=>res)
.catch(xhr=>xhr)
//url 请求的地址
//data 请求体(发送给服务器的数)
//.then 成功响应方法
//.catch 网络失败相应方法
//res 服务器返回的数据 response 响应的简历,是个形参起任何名字都可以
示列
//$.post("http:/ /520mg . com/ajax/ echo.php " , ' name=木木8age=18')
$.post("http://520mg.com/ ajax/echo.php" , { name:"木木" , age:18})
.then(res=>{
console.log(res)
})
.catch(xhr=>{
console.error(xhr)
})
$.ajax()方法
$.ajax()方法是jQuery的底层方法,可以传入定义的参数最多,更加灵活
jQ中的ajax方法是分3层封装的
- 第一层
$.ajax()
- 第二层
$.get();
$.post();
- 第三层
el.ioad()加载
$.getJSON()加载json数据的
$getScript()加载并执行js
语法
$.ajax({
url,
//请求的地址
method,
//请求的方:法get, post, deLete, put
data,
//请求的数据
dataType,
//返回数据列席json,jsonp, text
xhrFields: {withCredentials: true} ,
//用来跨域
success:function(res){},
//成功回调函数res服务器返回的数据,等同于.then
error:function(xhr){},//网络失败的回调函数,
})
.then(res=>res)
.catch(xhr=>xhr)
案例
$.ajax({
url : "https: / /528mg.com/member/index_login2.php",
method : "POST",
data: {dopost :"exit"},//退出和登录一个接口传递参数不一样
datalype : "json",//返回的数据格式是json
xhrFields: {withCredentials: true}/})
.then(res=>{
alert(res.msg);})
.catch(err=>console.error(err))
参数名 | 解释 | 示列 |
---|---|---|
url | 请求的地址 | = |
method | 请求的方法 | get.post.put.delete |
data | 请求的数据 | {name:"mumu}"age:18} |
dataType | 返回数据的类型 | xml,text,json,jsonp |
xhrFields | 携带请求头信息 (用来跨域) | {withCredentials:true} |
success | 成功的回调函数 | = |
error | 失败回调函数 | = |
brforeSend | 发送前的回调函数显示加载提示 | = |
complete | 加载完成回调函数关闭加载提示 | = |