zoukankan      html  css  js  c++  java
  • 2019.8.27更新:《Vue.js实战一书p231练习试做(3)

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

    此插件代码如下:(已测试可正常使用)

    const install=function(Vue,opotions={}){
        const ajax=new Vue({
            data(){
                return{
                    options:null,
                    data:'',
                    type:'GET',
                    url:'',
                    success:function(){},
                    error:function(){},
                    xhr:null
                    
                };
            },
            methods:{
                initialize(options){
                    this.setOptions(options);
                    //this.data=this.setData(this.options.data);
                    this.data=this.options.data;
                    this.type=this.options.type;
                    this.url=this.options.url;
                    this.success=this.options.success;
                    this.error=this.options.error;
                    this.xhr=this.createXHR();
                    this.start();
                },
                setOptions(options){
                    this.options={
                        type:'GET',
                        data:'',
                        success:function(mes){alert(mes)},
                        error:function(mes){alert(mes)},
                        url:''
                    };
                    Object.assign(this.options,options);
                    //for(var p in options) this.options[p]=opotions[p];
                },
                //把传入的数据设置为key1=value1&key2=value2格式的字符串,如果
                //是使用FormData对象生成数据,则可以不用,不然会出错
                setData(data){
                    let localdata=[];
                    for(let i in data){
                        localdata.push(encodeURIComponent(i) +
                        '='+encodeURIComponent(data[i]));
                    }
                    localdata=localdata.join('&');
                    return localdata;
                },
                createXHR(){
                    const _this=this;
                    const xhr = new XMLHttpRequest();
                    xhr.onreadystatechange=function(){
                        if(xhr.readyState==4){
                            const status=xhr.status;
                            if(status>=200 && status<300){
                                _this.success &&
                                _this.success(xhr.responseText);
                            }else{
                                _this.error &&
                                _this.error(status);
                            }
                        }
                    };
                    return xhr;
                },
                get(url){
                    this.xhr.open('get',url+'?'+this.data,true);
                    this.xhr.send(null);
                },
                post(url,mes){
                    this.xhr.open('post',url,true);
                    //this.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    this.xhr.send(mes);
                },
                start(){
                    switch(this.type.toUpperCase()){
                        case 'GET':
                            this.get(this.url);
                            break;
                        case 'POST':
                            this.post(this.url,this.data);
                            break;
                    }
                }
            },
            created(){
                this.initialize();
            }
        });
        Vue.prototype.$ajax=ajax;
    };
    export default install;

    使用方法:

    在main.js中导入 

    import VueAjax from './components/vue-ajax';
    Vue.use(VueAjax);

    在 .vue 格式文件中,

    <template>
      <div id="app">
        <form id="user-info">
            <label for="user-name">Name:</label><input type="text" id="user-name" name="user-name" /><br />
            <label for="user-email">Email:</label><input type="text" id="user-email" name="user-email" /><br />
            <input type="button" value="Submit" @click="submitData" />
        </form>
      </div>
    </template>
    <script>
    export default {
      methods:{
        submitData(){
          var form=document.getElementById('user-info');
          var objs={
            type:'post',
            url:'postexample.php',
            data:new FormData(form)
          }
          this.$ajax.initialize(objs);
        }
      },
      
    }
    </script>

    可以直接调用get/post,传入url/data

    也可以调用Initialize,传入一个参数对象

    this.$ajax.initialize(objs);
    this.$ajax.get('example.txt');
    this.$ajax.post('postexample.php',new FormData(form));
     
  • 相关阅读:
    快速幂(Fast Pow)
    半小时写完替罪羊重构点分树做动态动态点分治之紫荆花之恋的wyy贴心指导
    POJ2942 UVA1364 Knights of the Round Table 圆桌骑士
    二分图判定
    Tarjan求点双连通分量
    POJ1523 SPF 单点故障
    OI比赛常数优化
    Tarjan求割点
    NOIP2015 D1T1 神奇的幻方
    NOIP2016 D2T2 蚯蚓
  • 原文地址:https://www.cnblogs.com/sx00xs/p/11421460.html
Copyright © 2011-2022 走看看