【cocos2d-js網絡教程篇】cocos2d-js http網絡請求


前言

剛入手cocos2d-js,看到網上的JS的http網絡請求,大部分都是錯的。原因在於,js-tests里面的網絡請求實例沒有給出加載完成事件。正確的加載完成事件如下:

var xhr = cc.loader.getXMLHttpRequest();  
        xhr.open("POST", url);  
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");  
        xhr["onloadend"] = function(){  
};

Http.js完整類

var Http =  cc.Class.extend({  
    m_inst : null, //實例  
    url : "http://127.0.0.1:8080/request.php",  
  
    ctor : function(){  
    },  
  
      /*  
     * 網絡請求之GET  
     * url 請求的網絡地址  
     * callback 回調參數  
     * */  
    getWithUrl : function(url,callback){  
        var xhr = cc.loader.getXMLHttpRequest();  
        xhr.open("GET",url,true);  
        xhr["onloadend"] = function () {  
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) {  
                err = false;  
            }else{  
                err = true;  
            }  
            var response = xhr.responseText;  
            callback(err,response);  
        };  
        xhr.send();  
    },  
   
    /*  
     * 網絡請求之POST  
     * url 請求的網絡地址  
     * params  請求參數  ("id=1&id=2&id=3")  
     * callback 回調參數  
    ['loadstart', 'abort', 'error', 'load', 'loadend', 'timeout']  
    * */  
    sendWithUrl : function(url, params, callback){  
  
        var xhr = cc.loader.getXMLHttpRequest();  
        xhr.open("POST", url);  
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");  
        xhr["onloadend"] = function(){  
  
            var sc = -1  
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) {  
                sc = 0;  
            }  
  
            var json = JSON.parse(xhr.responseText)  
            var rc = parseInt(json["code"])  
  
            callback(sc, rc, json);  
  
            if(sc == 0 && (rc != 0) && RETCODE[rc + ""])  
            {  
                Alert.getInst().show(RETCODE[rc + ""])  
            }  
            else if(sc != 0 || rc != 0 ){  
                Alert.getInst().show("sc: " + sc + " rc: " + rc)  
            }  
        }  
       xhr.send(params);  
    }  
});  
  
//獲取實例  
Http.inst = function() {  
    if (Http.m_inst == null) {  
        Http.m_inst = new Http();  
    }  
    return Http.m_inst;  
};

使用方法

Http.inst()->sendWithUrl("http://127.0.0.1:8080/request.php", "id=1&id=2&id=3", function(sc, rc, response){  
  cc.log("返回數據" + response);  
});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM