在前端的快速發展中,爲了契合更好的設計模式,產生了Fetch框架,Fetch返回的信息比XMLHttpRequest更豐富。但它目前還不是一個標準,它支持大部分常用的http 請求和響應的標準。
一. 一個完整的post請求和響應的過程
var url = "/fetch";
fetch(url,{
method:"post",
headers:{
"Content-type":"application/x-www-form-urlencoded"
},
body:"name=luwenjing&age=22"
})
.then(function (response){
if (response.status == 200){
return response;
}
})
.then(function (data) {
return data.text();
})
.then(function(text){
console.log("請求成功,響應數據爲:",text);
})
.catch(function(err){
console.log("Fetch錯誤:"+err);
});
(1)fetch的參數有兩個,第一個是url即請求的處理路徑;
第二個是初始化信息,包括以下幾種:
- method:請求方法,常用的有get和post;
- headers:請求頭信息,最常用的就是表單格式的數據:”Content-type”:”application/x-www-form-urlencoded”;
- mode:控制是否允許跨域。same-origin(同源請求)、no-cors(默認)和cros(允許跨域請求);
- cache:關於緩存的一些設置;
- body:要發送到後臺的參數,可以爲ArrayBuffer,String,FormData等類型;
(2)從上面的代碼我們可以知道fetch()方法返回的是一個promise對象;
(3)響應信息爲傳入then方法成功時的參數,相應包含很多http的響應信息,如下:
(4)可以判斷響應的狀態嗎,返回請求成功的對應信息;
(5)通過狀態轉換,轉換爲指定的格式,如果是文本信息,直接text()方法就可以;若爲json格式,則json()就可以轉換爲json格式信息,其實也就是自己請求數據格式時所設置的格式;
二. 後臺處理代碼:
import java.io.IOException;
import java.io.Writer;
/**
* Created by LuWenjing on 2017/4/5.
*/
public class fetchServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
String name = request.getParameter("name");
String age = request.getParameter("age");
System.out.println(name + ": " + age);
Writer out = response.getWriter();
out.write("hello world!");
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doPost(request, response);
}
}
後臺成功輸出:
瀏覽器控制檯成功打印:
三. 和ajax 的對比
(1)上面的Fetch代碼很像jQuery中的ajax,但是兩者是不同的,fetch是原生的js,而jQuery中的ajax是庫封裝的;
(2)ajax只能實現同源請求,fetch可實現跨域請求;
(3)ajax幾乎所有的主流瀏覽器都支持,但fetch由於目前並沒有被列入標準,只有像firefox最新版,chrome最新版,以及IE10+等以上才支持,如下圖片所示;
注意:在body中向後臺傳遞參數時,只有寫成“key=value&key=value”的形式纔會成功,其它方法後臺接收到均爲null,封裝爲FormData格式也不成功。