《Vue.js实战一书p231练习试做

练习: 学习XMLHttpRequest (即XHR )相关知识,开发一个简单的 ajax 插件,用于异步获
取服务端数据。

解答:

书作者提供了一段代码作为参考,实际上是要求我们把这段代码封装起来,此插件会提供 2 个接口:get 和 post,接受一个字符串参数:url

const install = function(Vue, options={}){
   //辅助函数,用于创建 xhr对象,添加readystatechange事件处理函数
function createXhr(){ const xhr = new XMLHttpRequest(); xhr.onreadystatechange=function(){ if(xhr.response===4){ const status = xhr.status; if(status >= 200 && status < 300){ options.success && options.success(JSON.parse(xhr.responseText),xhr.responseXML); }else{ options.error && options.error(status); } } }; return xhr; }   //辅助函数,用于·创建传送给服务器的数据data function createData(){ const data =[]; for(let i in options.data){ data.push(encodeURIComponent(i) + '=' + encodeURIComponent(options.data[i])); } data=data.join('&'); return data; } const ajax = new Vue({ methods:{
       //接口1,接受url参数, get(url){ const xhr
= createXhr(); const data = createData(); xhr.open('GET', url + '?' + data, true); xhr.send(null); },
        //接口2,接受url参数 post(url){ const xhr
= createXhr(); const data = createData(); xhr.post('POST', url, true); xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-rulencoded' ); xhr.send(data); } } }); Vue.prototype.$ajax = ajax; }; export default install;

猜你喜欢

转载自www.cnblogs.com/sx00xs/p/11403250.html
今日推荐