version: cocos2d-x 3.6
1.使用http post Json与服务器交互require("src/cocos/cocos2d/Json")require("src/cocos/network/NetworkConstants")-- post Jsonlocal xhr = cc.XMLhttpRequest:new()xhr.responseType = cc.XMLhttpREQUEST_RESPONSE_JsONxhr:setRequestheader("Content-Type","application/Json")xhr:open("POST","www.baIDu.com")local function loginCallback() print("xhr.readyState is:",xhr.readyState,"xhr.status is: ",xhr.status) if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then local response = xhr.response local output = Json.decode(response) -- print table.foreach(output,function(i,v) print (i,v) end) -- success ... else -- fail ... endendxhr:registerScriptHandler(loginCallback)xhr:send(sendJson)2.使用http get下载网络图片
-- get (image)pSprite:retain() -- a spritelocal xhr = cc.XMLhttpRequest:new()-- tagxhr._urlfilename = urlfilenamexhr._urlSprite = pSpritexhr.responseType = cc.XMLhttpREQUEST_RESPONSE_STRINGxhr:open("GET","http://cocos2d-x.org/s/images/img-cocos2dx.jpg")local function onDownloadImage() print("xhr.readyState is:",xhr.status) if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then local fileData = xhr.response local fullfilename = cc.fileUtils:getInstance():getWritablePath() .. "/" .. xhr._urlfilename local file = io.open(fullfilename,"wb") file:write(fileData) file:close() local texture2d = cc.Director:getInstance():getTextureCache():addImage(fullfilename) local pSprite = xhr._urlSprite if texture2d then pSprite:setTexture(texture2d) end pSprite:release() -- be careful endendxhr:registerScriptHandler(onDownloadImage)xhr:send()在使用xhr时,可以添加自己的数据(如:
xhr._urlSprite = pSprite
),存放用户的临时数据,方便返回时使用。 总结 以上是内存溢出为你收集整理的cocos2d-x lua 使用http(下载图片, POST JSON)全部内容,希望文章能够帮你解决cocos2d-x lua 使用http(下载图片, POST JSON)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)