您的位置:首页 > 理论基础 > 计算机网络

cocos2dx lua http请求获取网络数据:

2017-06-06 16:24 537 查看
cocos2dx lua http请求获取网络数据:

[plain]
view plain
copy
print?

local xhr = cc.XMLHttpRequest:new() --创建一个请求  
xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING --设置返回数据格式为字符串  
local req = "http://www.XXX” --请求地址  
xhr:open("GET", req) --设置请求方式  GET     或者  POST  
  
local function onReadyStateChange()  --请求响应函数  
    if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then —请求状态已完并且请求已成功              local statusString = "Http Status Code:"..xhr.statusText  
            print("请求返回状态码"..statusString)  
            local s = xhr.response —获得返回的内容  
            print(“返回的数据")   
    end  
end  
xhr:registerScriptHandler(onReadyStateChange) --注册请求响应函数  
xhr:send() —最后发送请求  

注:
请求状态  xhr.readyState == 4 

0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
数据返回格式  xhr.responseType
cc.XMLHTTPREQUEST_RESPONSE_STRING = 0 -- 返回字符串类型
cc.XMLHTTPREQUEST_RESPONSE_ARRAY_BUFFER = 1 -- 返回字节数组类型

cc.XMLHTTPREQUEST_RESPONSE_BLOB = 2 -- 返回二进制大对象类型

cc.XMLHTTPREQUEST_RESPONSE_DOCUMENT = 3 -- 返回文档对象类型

cc.XMLHTTPREQUEST_RESPONSE_JSON = 4 -- 返回JSON数据类型
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: