首页 > Web开发 > 详细

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

时间:2019-08-24 10:08:37      阅读:105      评论:0      收藏:0      [点我收藏+]

练习: 学习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;

 

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

原文:https://www.cnblogs.com/sx00xs/p/11403250.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!