下面是cocos2d-js请求网络数据的代码:
var HttpRequest = { /* * 网络请求之GET * url 请求的网络地址 * callback 回调参数 * */ GET:function(url,callback){ var xhr = cc.loader.getXMLHttpRequest(); xhr.open("GET",url,true); xhr.onreadystatechange = functio/本2文来源[email protected]搞@^&代*@码2网搞gaodaima代码n () { if (xhr.readyState == 4 && (xhr.status >= 200 && 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); } }) */
但是,请求网络出现了:No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:63342’ is therefore not allowed access.
这是因为浏览器不能跨域访问,我们在服务端找到这个要请求的文件:设置一下header
<?php header("Access-Control-Allow-Origin : *");echo "I Love you"?>
这样,就成功返回了数据?但是!!!,没有成功,晕,原因是这个php调用header之前不能有任何输出,必须改编码为UTF-8 无rom格式,弄了一晚上卡在这个点上!!!
以上就介绍了cocos2d-js跨域访问问题,cocos2d-js请求网络数据,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。