The following is the code for cocos2d-js to request network data:
var HttpRequest = { /* * 网络请求之GET * url 请求的网络地址 * callback 回调参数 * */ GET:function(url,callback){ var xhr = cc.loader.getXMLHttpRequest(); xhr.open("GET",url,true); xhr.onreadystatechange = 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 回调参数 * */ POST:function(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","text/plain;charset=UTF-8"); xhr.onreadystatechange = 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(params); } } //EXMAPLE /* HttpRequest.POST("http://127.0.0.1:3000/test","id=1&ids=2", function(err,data){ if(err){ //错误处理 }else{ cc.log(data); } }) */
This is because the browser cannot access cross-domain. We find the file to be requested on the server side: set the header
<?php header("Access-Control-Allow-Origin : *"); echo "I Love you" ?>
The above introduces the cross-domain access issue of cocos2d-js. Cocos2d-js requests network data, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.