Vue封裝完善ajax

HTML文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <button @click="getInfo">點擊獲取信息</button>
        <span>{{ msg }}</span>
    </div>

    <script src="vue.js"></script>
    <script src="vue-ajax.js"></script>
    <script>
        var vm=new Vue({
            el: "#app",
            data: {
                msg: "",
            },
            methods: {
                getInfo: function (){
                    var self=this;
                    this.ajax.get("1.json",{
                        tel: 123456,
                        address: "杭州"
                    },function (data){
                        self.msg=data[1].name
                    },"json");
                }
            }
        })
    </script>
</body>
</html>

JS文件:

/*
* ajax封裝:
* 1. 引入文件
* 2. new Vue().ajax.get(url,data,fn,ojson), 或 new Vue().ajax.post(url,data,fn,ojson)
*     url: 須要獲取數據的文件地址 (string)
*     data: 須要發送的信息 (可省略) (obj)
*     fn: 獲取信息後的回調函數,接收到的返回值爲data (function)
*     ojson: 是否須要轉換爲json格式 (可省略) (設置爲 "json")
*
* 3. new Vue().ajax.get().cancel(): 取消異步請求
* 4. new Vue().ajax.json(str): 可轉化json格式字符串
**/
Vue.prototype.ajax={
    //添加url傳送信息
    addUrl: function (url,obj){
        //若是省略url,則爲post請求,令obj爲url,令url爲null
        if(arguments.length==1){
            obj=url;
            url=null;
        }
        //url不爲空(get請求: 設置url信息)
        if(!!url){
            for(var k in obj){
                url += (url.indexOf("?")==-1 ? "?" : "&");
                url+=encodeURIComponent(k)+ "=" +encodeURIComponent(obj[k]);
            }
        }else{
            //post請求(設置data信息)
            url="";
            for(var k in obj){
                url+=encodeURIComponent(k)+ "=" +encodeURIComponent(obj[k]);
                url+="&";
            }
            //刪除最後一個&
            var arr=url.split("");
            arr.pop();
            url=arr.join("");
        }
        //返回拼接好的信息
        return url;
    },
    get: function (url,data,fn,ojson){
        this.xhr=new XMLHttpRequest();
        //省略data時,即不發送數據
        if(typeof data =="function"){
            ojson=fn;
            fn=data;
            data={};
        }
        //合併url和data信息
        url=this.addUrl(url,data)
        //是否異步發送
        this.xhr.open("get",url,true);
        this.xhr.send(null);
        //當請求完成以後調用回調函數返回數據
        this.success(fn,ojson);
        //鏈式編程
        return this;
    },
    post: function (url,data,fn,ojson){
        this.xhr=new XMLHttpRequest();
        //省略data時,即不發送數據
        if(typeof data =="function"){
            ojson=fn;
            fn=data;
            data={};
        }
        //合併data信息
        data=this.addUrl(data);
        //是否異步發送
        this.xhr.open("post",url,true);
        this.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        this.xhr.send(data);

        //當請求完成以後調用回調函數返回數據
        this.success(fn,ojson);
        //鏈式編程
        return this;
    },
    //字符串轉換json
    json: function (str){
        return (new Function("return " + str))(); 
    },
    success: function (fn,ojson){
        //當請求完成以後調用回調函數返回數據
        var self=this;
        this.xhr.onreadystatechange=function (){
            var odata;
            if(self.xhr.readyState == 4){
                if((self.xhr.status>=200 && self.xhr.status<300) || self.xhr.status == 304){
                    odata=self.xhr.responseText;
                    //若爲json則轉化json格式
                    if(ojson==="json"){
                        odata=self.json(odata);
                    }
                    fn(odata);
                }else{
                    odata="request was unsuccessful: "+self.xhr.status;
                    fn(odata);
                }
            }
        }
    },
    //取消異步請求
    cancel: function (){
        this.xhr.abort();
        return this;
    }
}

後臺獲取或者前端構造的數據結構:

[
    {
        "name": "張三",
        "age": 18,
        "sex": "man"
    },
    {
        "name": "李四",
        "age": 20,
        "sex": "woman"
    },
    {
        "name": "王五",
        "age": 22,
        "sex": "man"
    }
]
相關文章
相關標籤/搜索