**
HTTP
**
http的请求过程
请求头的组成
响应头的组成
请求方法
响应码
XMLHTTPRequst
get请求
post请求
JQuery中的ajax
.load方法
语法
el.load(url)
把url通过ajax加载到内部
事例
**$(".container").load("./xxx.txt")
**
get 请求方法
通过get请求方式获取内容
语法
$.get(url)
.then(res=>)
.catch(xhr=>xhr)
...
>.thend 的前面一行没分号结尾
**向服务器请求一条笑话信息**
**$.get(‘http://520mg.com/mi/list。php?page=1’)
.then(res=>){
// res 就是服务器返回内容
// then就是请求成功后获取内容的方法
}
.catch(xhr=>){
//.catch 就是请求失败(通常是网络错误响应方法
//xhr就是jquery 封禁的XMLHTTPRquest 对象
}
**
### $post 方法
以post方法向服务器发起请求
语法
$.post(url,data)
.then(res=>)
.catch(xhr=>xhr)
// url 请求的地址
// data 请求体
// .then 成功响应方法
// .catch 网络失败响应方法
// res服务器返回的数据 response 的简写 是个形参 任何名字都可以
示例
$.post(‘http://520mg.com/ajax/echo.php’)
.then(res=>{
console.log(res)
}
)
.catch(xhr=>{
console.error(xhr)
})
$ajax 方法
$.ajax()方法是底层方法 可以传入的定义参数最多 更加灵活
jq中的ajax 方法是分三层 封装的
- 第一层$.ajax()
- 第二层 $.get()
- $.post()
- 第三层
- el.load 加载
- $.getJSON()加载json数据的
- $.getScript()加载并执行js
语法
$.ajax({
url// 请求的地址
method // 请求的方法
data. // 请求的数据
dataType //返回数据列席
xhrFields (withCredentials:true) //用来跨域
success(function(res){} )// 成功回调函数res服务器返回的数据
error :function(xhr){} // 网络失败的回调函数 等同于catch
})
.then(res=>res)
.catch(xhr=>xhr)
案列
$.ajax({
url: "https://520mg.com/member/index_login2.php",
method: "POST",
data: {
dopost: "exit"
}, //退出和登录一个接口传递参数不一样
dataType: "json", //返回的数据格式是json
xhrFields: {
withCredentials: true, //把本地127.0.0.1的cookie发送给520mg.com
}
})
then(res => {
alert(res.msg);
.catch(err => {
console.log("网络请求失败")
})