zoukankan      html  css  js  c++  java
  • Laya 使用get或post请求服务器

    export default class Request {
        private _http;
        private _server = "https://test.codeplanet.cc";//
        static _instance = null;
      //把自己设置为单例模式,不销毁则一直存在
        static getInstance(): Request {
            if (!Request._instance) {
                Request._instance = new Request;
            }
            return Request._instance;
        }
        set server(str: string) {
            this._server = str;
        }
        /**
         * 
         * @param url {string} url地址
         * @param data {object} 参数
         * 
         */
        post(params) {
            this._http = new Laya.HttpRequest();
            let requst = new Promise((resolve, reject) => {
                this._http.once(Laya.Event.COMPLETE, this, e => { resolve(this.onCompleteHanlder(e)) })
            })
            let data = this.parseParam(params.data) || {};
            let url = this.getServerFullUrl(params.url)
            this._http.send(url, data, 'post', 'text');
            return requst;
        }
        get(params) {
            this._http = new Laya.HttpRequest();
            let requst = new Promise((resolve, reject) => {
                this._http.once(Laya.Event.COMPLETE, this, e => { resolve(this.onCompleteHanlder(e)) })
            })
            let data = this.parseParam(params.data) || {};
            this._http.send(params.url, data, 'get', 'text');
            return requst;
        }
        private onCompleteHanlder(e: any) {
            return JSON.parse(e);
        }
        private parseParam(data) {
            var body = '';
            for (var i in data) {
                body += i + "=" + data[i] + "&"
            }
            return body.slice(0, -1);
        }
        private getServerRootUrl() {
            return this._server ? this._server : window.location.origin;
        }
        private getServerFullUrl(partUrl) {
            let root = this.getServerRootUrl();
            if (root) {
                console.log('getServerFullUrl ' + root + partUrl);
                return root + partUrl;
            }
            return partUrl;
        }
    }
    //调用
    import Request from "../tools/Request";//引用request文件
    private _request: Request = Request.getInstance();

    this._request.post({ "/home/index", {type:1} }).then(res => {
        
    })
     
  • 相关阅读:
    【JZOJ5771】遨游【二分】【DFS】
    【JZOJ5773】简单数学题【数论,数学】
    【JZOJ5773】简单数学题【数论,数学】
    有效壳第2部分:成为一个剪贴板体操运动员
    具有多重选择和列表间拖拽的拖拽列表框
    将枚举绑定到下拉列表框并根据值对其排序
    一个具有子项格式的自定义绘制列表控件
    基本的c#屏幕截图应用程序
    将组合框下拉列表宽度调整为最长字符串宽度
    在应用程序中使用按钮控件
  • 原文地址:https://www.cnblogs.com/cubesugarnuo/p/12362951.html
Copyright © 2011-2022 走看看