Ajax与Fetch
发布时间:2020-12-16 01:41:30 所属栏目:百科 来源:网络整理
导读:介绍 页面中需要向服务器请求数据时,基本上都会使用Ajax来实现。Ajax的本质是使用XMLHttpRequest对象来请求数据。XMLHttpRequest的使用如下: var xhr = new XMLHttpRequest();xhr.open('GET',url,true);xhr.onload = function() { console.log(xhr.respons
介绍页面中需要向服务器请求数据时,基本上都会使用Ajax来实现。Ajax的本质是使用XMLHttpRequest对象来请求数据。XMLHttpRequest的使用如下: var xhr = new XMLHttpRequest(); xhr.open('GET',url,true); xhr.onload = function() { console.log(xhr.response); }; xhr.onerror = function() { console.error('error'); }; xhr.send(); 可以看出,XMLHttpRequest对象是通过事件的模式来实现返回数据的处理的。目前还有一个是采用Promise方式来处理数据的,这个技术叫做Fetch。 Fetch的使用使用Fetch实现请求的最基本代码: fetch(url).then(function (response) { return response.json(); // json返回数据 }).then(function (data) { console.log(data); // 业务逻辑 }).catch(function (e) { console.error('error'); }) 使用ES6的箭头函数后,可以更加简洁: fetch(url).then(response => response.json()) .then(data => console.log(data)) .catch(e => console.error('error')); 还可以使用ES7的async/await进一步简化代码: try { let response = await fetch(url); let data = response.json(); console.log(data); } catch(e) { console.log('error'); } 这样,异步的请求可以按照同步的写法来写了。 Fetch修改head信息fetch方法中还有第二个参数,第二个参数是用于修改请求的Head信息的。可以在里面指定method是GET还是POST;如果是跨域的话,可以指定mode为cors来解决跨域问题。 var headers = new Headers({ "Origin": "http://taobao.com" }); headers.append("Content-Type","text/plain"); var init = { method: 'GET',headers: headers,mode: 'cors',cache: 'default' }; fetch(url,init).then(response => response.json()) .then(data => console.log(data)) .catch(e => console.error('error')); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |