前端之家收集整理的这篇文章主要介绍了
cocos2dx 连接php,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
#include "HelloWorldScene.h"
#include "AppMacros.h"
#include "pthread.h"
#include "Json.h"
USING_NS_CC;
CCScene* HelloWorld::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::create();
// 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
void HelloWorld::onHttpRequestCompleted(CCHttpClient *sender,CCHttpResponse *response)
{
if (!response)
{
return;
}
// You can get original request type from: response->request->reqType
if (0 != strlen(response->getHttpRequest()->getTag()))
{
CCLog("%s completed",response->getHttpRequest()->getTag());
}
int statusCode = response->getResponseCode();
//char statusString[64] = {};
//sprintf(statusString,"HTTP Status Code: %d,tag = %s",statusCode,response->getHttpRequest()->getTag());
//m_labelStatusCode->setString(statusString);
CCLog("response code: %d",statusCode);
if (!response->isSucceed())
{
CCLog("response Failed");
CCLog("error buffer: %s",response->getErrorBuffer());
return;
}
// dump data
std::vector<char> *buffer = response->getResponseData();
std::string infoStr = string(buffer->begin()+5,buffer->end());
CCLog("a");
const char* _ch = infoStr.c_str();
CCLog(infoStr.c_str());
CCLog(_ch);
Json* myjson = Json_create(_ch);
const char* _ch1= Json_getString(myjson,"name","");
CCLog(_ch1);
//m_labelStatusCode->setString(infoStr.c_str());
}
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
CCSize visibleSize = CCDirector::sharedDirector()->getWinSize();
CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
{
CCHttpRequest* request = new CCHttpRequest();
request->setUrl("http://192.168.0.148/PHPProject/test1.PHP?user=wu");
request->setRequestType(CCHttpRequest::kHttpGet);
request->setResponseCallback(this,httpresponse_selector(HelloWorld::onHttpRequestCompleted));
request->setTag("GET test1");
CCHttpClient::getInstance()->send(request);
request->release();
}
return true;
}
void HelloWorld::menuCloseCallback(CCObject* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
#endif
}
bool HelloWorld::ccTouchBegan( CCTouch* touch,CCEvent* event )
{
CCLog("touchBegan1");
return true;
}
<?PHP
header("Access-Control-Allow-Origin: *");
if(isset($_GET['user'])){
$_arr = array('id' => 1,'name' => 'wuhongxing','age' => 20,'sex' =>0);
$_arr = json_encode($_arr);
echo $_arr;
}
else{
echo "请先登录该网站";
}
?>
如果前面出现几个识别不了的字符, 再sublime中保存编码为utf-8
原文链接:https://www.f2er.com/cocos2dx/346214.html