Cocos2d-x Lua API对XMLHttpRequest
对象进行了移植,可利用XMLHttpRequest
对象使用HTTP协议对Web服务器进行数据交互。Cocos2d-x Lua中的XMLHttpRequest
底层是HttpRequest
,在Lua中被重新封装。
使用Lua发送GET请求
-- 创建XMLHttpRequest对象
local xhr = cc.XMLHttpRequest:new()
-- 设置xhr的应答类型
xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_JSON
-- 与Web服务器建立HTTP连接
local url = "http://host.com/parameter"
xhr.open("GET", url)
-- Web服务器处理完后调用
local function onReadyStateChange()
if xhr.readyState==4 and xhr.status==200 then
-- 获取Web服务器返回的JSON数据
local responseData = xhr.response
if responseData then
local ok,data = pcall(function()
local json = require("json")
return json.decode(responseData)
end)
if not ok then
print("response data error")
data = nil
end
end
end
end
-- 注册请求Web服务器事件
xhr:registerScriptHandler(onReadyStateChange)
-- 向Web服务器发送请求
xhr:send()
使用Lua发送POST请求
local json = require("json")
-- 创建XMLHttpRequest对象
local xhr = cc.XMLHttpRequest:new()
-- 设置xhr请求头的内容类型
xhr.setRequestHeader("Content-Type", "application/json")
-- 设置xhr的应答类型
xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_JSON
-- 与Web服务器建立HTTP连接
local url = "http://host.com/parameter"
xhr.open("POST", url)
-- Web服务器处理完后调用
local function onHttpRequestCompleted()
if xhr.readyState==4 and xhr.status==200 then
-- 获取Web服务器返回的JSON数据
local responseData = xhr.response
if responseData then
local ok,data = pcall(function()
return json.decode(responseData)
end)
if not ok then
print("response data error")
data = nil
end
end
end
end
-- 注册请求Web服务器事件
xhr:registerScriptHandler(onHttpRequestCompleted)
-- 拼装数据
local data = {uid = 100}
-- 向Web服务器发送请求
xhr:send(json_encode(data))
XMLHttpRequest
对象属性和方法
-
open(requestType, url, asynch, username, password)
与服务端连接并创建新的请求,XMLHttpRequest
提供GET
和POST
两种HTTP请求方式。 -
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数据类型 -
setRequestHeader()
设置请求头信息
xhr:setRequestHeader("Content-Type", "application/json")
-
send()
向服务端发送请求 -
abort()
退出当前请求 -
readyState
当前请求的就绪状态,4表示准备就绪。 -
status
当前请求状态码,200表示请求成功。 -
responseText
服务器返回响应文本 -
onReadyStateChange
设置回调函数,当服务器处理完请求后会自动调用此回调函数。 -
registerStateChange(callback)
注册回调函数,但消息发生响应后触发调用。