页面中须要向服务器请求数据时,基本上都会使用Ajax来实现。Ajax的本质是使用XMLHttpRequest对象来请求数据。XMLHttpRequest的使用以下:json
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(url).then(function (response) { return response.json(); // json返回数据 }).then(function (data) { console.log(data); // 业务逻辑 }).catch(function (e) { console.error('error'); })
使用ES6的箭头函数后,能够更加简洁:app
fetch(url).then(response => response.json()) .then(data => console.log(data)) .catch(e => console.error('error'));
还可使用ES7的async/await进一步简化代码:cors
try { let response = await fetch(url); let data = response.json(); console.log(data); } catch(e) { console.log('error'); }
这样,异步的请求能够按照同步的写法来写了。异步
fetch方法中还有第二个参数,第二个参数是用于修改请求的Head信息的。能够在里面指定method是GET仍是POST;若是是跨域的话,能够指定mode为cors来解决跨域问题。async
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'));