什么是fetch? fetch,说白了,就是XMLHttpRequest的一种替代方案。如果有人问你,除了Ajax获取后台数据之外,还有没有其他的替代方案?这时你就可以回答:有!那就是------fetch

工具/原料
一台电脑
一个浏览器
fetch基本说明
1、fetch的基本语法fetch(url,init).then(function(response){ } )

2、fetch的参数说明① fetch接收两个参数,第一个为地址且必填,第二个为配置对象可选。② 如果是简单的无参数get请求,那么可以不要第二个参数(默认为get请求),当然也可以加上来对此fetch进行一些说明③ 第二个参数包含请求类型,发送数据,headers,模式等④ fetch方法返回的也是一个promise对象,我们只能使用then来获取返回数据,⑤ 我们需要两次then才能对后台返回得到数据进行处理,在第一个then里面return result.text(), 或者 return result.json(),然后第二个参数里面才能真正的获取到返回的具体值,并且对其进行逻辑处理如果要判断请求是否失败,那么请在第一次的then里面判断,那里面为请求数据对象。


fetch使用实例
1、使用fetch访问php接口//get请求var res=fetch("http://www.blogzl.com/zl_other_module/ajaxTest/getTest.php?doWhat=张三");var res1=res.then(function(e){return e.text();});var res2=res1.then(function(e){console.info(e)});

2、使用fetch访问php接口--- post//post请求var obj={doWhat:"张三"}//声明参数var result = fetch('http://www.blogzl.com/zl_other_module/ajaxTest/postTest.php',{method:'POST',body:JSON.stringify(obj)//将参数转换为字符串传入后台});result.then(function(res){return res.text();}).then(function(text){console.info(JSON.parse(text));});

3、使用fetch 访问nodejs接口--- post需要加上代码:"Content-T鲻戟缒男ype": "application/json"// fetch(url,init).then(function(response){ } )varparobj= JSON.stringify({ key:"123456"});fetch("http://127.0.0.1:8081/check", {method:"post",headers:{"Accept":"application/json","Content-Type":"application/json"},body:parobj,}).then(function(data) {returndata.json()}).then(function(data) {console.log(data);})

4、使用fetch连续发起多次请求如果要使用fetch发起多次请求,那么从第二次开始我们就要把每次的then方法执行后的promise 对象返回。//第一次请求varres=fetch("http://127.0.0.1:8081/").then(function(e){returne.json();}).then(function(e){console.log("第一次请求结果的值为:",e);returne;})//第二次请求varres2=res.then(function(d){if(d.data=="get"){returnfetch("http://127.0.0.1:8081/",{method:"post"}).then(function(e){returne.json();}).then(function(e){console.log("第二次请求结果的值为:",e);returne;})}});//第三次请求varres3=res2.then(function(d){if(d.data=="post"){returnfetch("http://127.0.0.1:8081/",{method:"get"}).then(function(e){returne.json();}).then(function(e){console.log("第三次请求结果的值为:",e);returne;})}});//获取第三次请求的数据varres3=res2.then(function(d){console.log("第三次请求结果的值为:",d);});
