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