Ajax 和 Fetch
ajax
异步请求数据的web开发技术,不需要刷新页面的前提下加载后台数据
- 提高用户体验,减少网络数据传输量
Ajax原生
-
核心对象
new XMLhttpRequest()--兼容性:new ActiveXObject("Microsoft.XMLHTTP") -
发起请求:
.open( method,url,async ),请求方法、路径、是否异步 -
当
async=true时,使用onreadystatechange函数,每当readyState改变都会触发函数 -
readyState状态(事件函数被触发4次:0-1、1-2、2-3、3-4):- 0: 请求未初始化
- 1: 服务器连接已建立
- 2: 请求已接收
- 3: 请求处理中
- 4: 请求已完成,且响应已就绪
-
status:200表示ok、404表示未找到页面 -
post请求:使用.setRequestHeader(header,value)添加请求头Accept:浏览器能够处理的内容类型;Accept-Charset: 浏览器能够显示的字符集;Accept-Encoding:浏览器能够处理的压缩编码;Accept-Language:浏览器当前设置的语言;Connection:浏览器与服务器之间连接的类型;Cookie:当前页面设置的任何Cookie;Host:发出请求的页面所在的域;Referer:发出请求的页面URI;User-Agent:浏览器的用户代理字符串;
-
发送到服务器:
.send(string),string仅用在post请求 -
响应数据:responseText、responseXML
实例
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest()
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
xhr.onreadystatechange=function(){
if(xhr.status === 200 && xhr.readyState === 4){
console.log(this.responseText);
const textAjax = JSON.parse(this.responseText)
console.log(textAjax);
}
}
xhr.open("get","jsonText.json",true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send()
//发送json数据(字符串转json)
//.send(JSON.stringify({ "email": "admin@runoob.com", "response": { "name": "runoob" } }))
jquery里的ajax
常用:
async布尔值,表示请求是否异步处理。默认是 true。type规定请求的类型(GET 或 POST)。url规定发送请求的 URL。默认是当前页面。timeout设置本地的请求超时时间(以毫秒计)。data规定要发送到服务器的数据。dataType预期的服务器响应的数据类型。jsonp在一个 jsonp 中重写回调函数的字符串。jsonpCallback在一个 jsonp 中规定回调函数的名称。beforeSend(*xhr*)发送请求前运行的函数。cache布尔值,表示浏览器是否缓存被请求页面。默认是 true。complete(*xhr,status*)请求完成时运行的函数(在请求成功或失败之后均调用,即在 success 和 error 函数之后)。contentType发送数据到服务器时所使用的内容类型。默认是:"application/x-www-form-urlencoded"。context为所有 AJAX 相关的回调函数规定 "this" 值。success(*result,status,xhr*)当请求成功时运行的函数。error(*xhr,status,error*)如果请求失败要运行的函数。dataFilter(*data*,*type*)用于处理 XMLHttpRequest 原始响应数据的函数。 不常用:global布尔值,规定是否为请求触发全局 AJAX 事件处理程序。默认是 true。ifModified布尔值,规定是否仅在最后一次请求以来响应发生改变时才请求成功。默认是 false。password规定在 HTTP 访问认证请求中使用的密码。processData布尔值,规定通过请求发送的数据是否转换为查询字符串。默认是 true。scriptCharset规定请求的字符集。traditional布尔值,规定是否使用参数序列化的传统样式。username规定在 HTTP 访问认证请求中使用的用户名。xhr用于创建 XMLHttpRequest 对象的函数。
代码实现(操作方式)
- $.ajax({})
$.ajax({
type : "POST", //以post方法提交数据给服务器
url : "User", //提交数据到User
dataType : "text", //数据类型
data : { //传给服务器的数据
"name": $("#name").val(),
"password":$("#pwd").val()
},
success:function(msg) { //回调函数
if(msg =="OK"){
alert("登录成功!");
}
else{
alert("登录失败!");
}
}});
- $.post()
$.post(
"/uyser/update",
{name: 'jim'},
function(data) {
//data为 后台传回的数据 json 格式
},
"json"
);
- $.get()
$.get(
"/user/selete",
{name: 'jim'},
function(data) {
//data为 后台传回的数据 json 格式
},
"json"
);
Fetch
- fetch请求使用ES6新增语法--Promise:Promise是一个对象,从它可以获取异步操作的消息,原型上有then、catch等方法,可以对结果进行链式调用而不是用传统的回调函数,这使得代码更加简洁。(Promise语法非常重要)
请求方式
fetch(url,options).then((response)=>{
//处理http响应
},(error)=>{
//处理错误
})
fetch参数
- url :是发送网络请求的地址。
- options:发送请求参数
- body -http请求参数
- mode -指定请求模式。默认值为cros:允许跨域;same-origin:只允许同源请求;no-cros:只限于get、post和head,并且只能使用有限的几个简单标头。
- cache -用户指定缓存。
- method -请求方法,默认GET
- signal -用于取消 fetch
- headers -http请求头设置
- keepalive -用于页面卸载时,告诉浏览器在后台保持连接,继续发送数据。
- credentials -cookie设置,默认omit,忽略不带cookie,same-origin同源请求带cookie,inclue无论跨域还是同源都会带cookie。
返回对象response
响应 response 对象:
- status - http状态码,范围在100-599之间
- statusText - 服务器返回状态文字描述
- ok - 返回布尔值,如果状态码2开头的,则true,反之false
- headers - 响应头
- body - 响应体。响应体内的数据,根据类型各自处理。
- type - 返回请求类型。
- redirected - 返回布尔值,表示是否发生过跳转。
response处理数据方法
response 对象根据服务器返回的不同类型数据,提供了不同的读取方法。分别有:
response.text()-- 得到文本字符串response.json()- 得到 json 对象response.blob()- 得到二进制 blob 对象response.formData()- 得到 fromData 表单对象response.arrayBuffer()- 得到二进制 arrayBuffer 对象
注意:返回的都是 promise 对象,必须等到异步操作结束,才能得到服务器返回的完整数据。
修改headers头部方法
const response = await fetch(url);
response.headers.get():根据指定的键名,返回键值。response.headers.has():返回一个布尔值,表示是否包含某个标头。response.headers.set():将指定的键名设置为新的键值,如果该键名不存在则会添加。response.headers.append():添加标头。response.headers.delete():删除标头。response.headers.keys():返回一个遍历器,可以依次遍历所有键名。response.headers.values():返回一个遍历器,可以依次遍历所有键值。response.headers.entries():返回一个遍历器,可以依次遍历所有键值对([key, value])。response.headers.forEach():依次遍历标头,每个标头都会执行一次参数函数。
fetch请求方式
- fetch请求默认发出 GET 请求,无论请求成功还是失败,都会
返回一个 Promise 对象
fetch('http://localhost:5555/dictItem/getAll')
.then(function(response){
return response.json();
})
.then(myJson=>{
//相关逻辑
})
- 使用
post请求
fetch(`http://localhost:80/ES6练习题/53fetch.html`,{
method:'POST',
headers:{
'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'
},
body:`user=${user.value}&pas=${pas.value}`
// 提交json数据进行转换:body:JSON.stringify(json)
// 提交表单数据:body:new FormData(form)
}).then(response=>{
console.log('响应',response)
})
发送表单数据:
const input = document.querySelector('input[type="file"]');
const data = new FormData();
data.append('file', input.files[0]);
data.append('user', 'foo');
fetch('/avatars', {
method: 'POST',
body: data
});
put请求
fetch('http://localhost:5555/dictItem/editDict/',{
method:'put',
body:JSON.stringify(this.editForm),
headers: {
'Content-Type': 'application/json'
}
}).then(response=>{ return response.text()})
.then(ret=>{
//相关逻辑
})
delete请求
fetch('http://localhost:5555/dictItem/'+row.id,{
method:'delete'
}).then(res=>{return res.text()})
.then(ret=>{
//相关逻辑
})
- 请求成功/失败的时候都会返回promise对象,then方法接收两个函数作为参数,第一个参数是 Promise 执行成功时的回调函数resolve,(resolve函数的参数就是Response 对象,所以要明白then方法中的res其实就是Response),第二个参数是 Promise 执行失败时的回调函数reject,两个函数只会有一个被调用。
awite改写fetch
function getList() {
try {
let res = await fetch("http://jsonplaceholder.typicode.com/posts");
let data = res.json(); console.log(data);
}
catch (error) { console.log(error); }
}
爬坑
1、fetch默认不带cookie
传递cookie时,必须在header参数内加上 credentials:'include',才会像 xhr 将当前cookie 带有请求中。
2、异常处理
fetch 不同于 xhr ,xhr 自带取消、错误等方法,所以服务器返回 4xx 或 5xx 时,是不会抛出错误的,需要手动处理,通过 response 中的 status 字段来判断