This article by qinning199 Original, reprint please specify: http://www.cocos2dx.net/post/216
Research the HTTP network request of COCOS2D-JS, very simple
1, get request, the code is as follows
var xhr = Cc.loader.getXMLHttpRequest (); var Statusgetlabel = new CC. Labelttf ("Status:", "Thonburi", 18); This.addchild (Statusgetlabel, 1); statusgetlabel.x = WINSIZE.WIDTH/2; Statusgetlabel.y = winsize.height-100; Statusgetlabel.setstring ("Status:send Get Request to httpbin.org"); Set arguments with <url>?xxx=xxx&yyy=yyy xhr.open ("GET", "Http://httpbin.org/get?show_env=1", true); Xhr.onreadystatechange = function () {if (xhr.readystate = = 4 && (xhr.status >= && ; Xhr.status <= 207) {var httpstatus = Xhr.statustext; var response = xhr.responseText.substring (0, 100) + "..."; var responselabel = new CC. Labelttf ("GET Response (chars): \ n" + Response, "Thonburi", 16); That.addchild (Responselabel, 1); Responselabel.anchorx = 0; Responselabel.anchory = 1; Responselabel.textalIGN = cc. Text_alignment_left; responselabel.x = 10; Responselabel.y = WINSIZE.HEIGHT/2; Statusgetlabel.setstring ("Status:got GET response!" + httpstatus); } }; Xhr.send ();
2, the POST request, the code is as follows
var xhr = Cc.loader.getXMLHttpRequest (); var Statuspostlabel = new CC. Labelttf ("Status:", "Thonburi", 18); This.addchild (Statuspostlabel, 1); statuspostlabel.x = WINSIZE.WIDTH/2; Statuspostlabel.y = winsize.height-140; Statuspostlabel.setstring ("Status:send Post Request to httpbin.org with plain text"); Xhr.open ("POST", "http://httpbin.org/post"); Set Content-type "Text/plain;charset=utf-8" to post plain text xhr.setrequestheader ("Content-type", "text/plain;ch Arset=utf-8 "); Xhr.onreadystatechange = function () {if (xhr.readystate = = 4 && (xhr.status >= && xhr. Status <= 207) {var httpstatus = Xhr.statustext; var response = xhr.responseText.substring (0, 100) + "..."; var responselabel = new CC. Labelttf ("POST Response (chars): \ n" + Response, "Thonburi", 16); That.addchild (Responselabel, 1); ResponselabEl.anchorx = 0; Responselabel.anchory = 1; Responselabel.textalign = cc. Text_alignment_left; responselabel.x = WINSIZE.WIDTH/10 * 3; Responselabel.y = WINSIZE.HEIGHT/2; Statuspostlabel.setstring ("Status:got POST response!" + httpstatus); } }; Xhr.send ("Plain text message");
"Cocos2d-js Tutorial" Cocos2d-js HTTP Network request