cocosCreator Http请求工具类


const HttpHelper = cc.Class({
    extends: cc.Component,

    /**
     * get请求
     * @param {string} url 
     * @param {function} callback 
     */
    get(url, callback) {
        var xhr = cc.loader.getXMLHttpRequest();
        console.log("Status: Send Get Request to " + url);
        xhr.open("GET", url, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status <= 207)) {  
                callback(true,xhr.responseText); 
            } 
        };
        xhr.send();
    },

    /**
     * post请求
     * @param {string} url 
     * @param {object} params 
     * @param {function} callback 
     */
    post(url, params, callback) {
        var nums = arguments.length  
        if(nums == 2){  
            callback = arguments[1];  
            params = "";  
        }  
        var xhr = cc.loader.getXMLHttpRequest();  
        xhr.open("POST", url);  
        xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8");  
        xhr.onreadystatechange = function () {  
            if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status <= 207)) {  
                callback(true,xhr.responseText); 
            }
        };  
        xhr.send(params); 
    }
     // update (dt) {},
});

window.HttpHelper = new HttpHelper();


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM