XMLHttpRequest
---------------------------------------------- -- 数据转换,将请求数据 由table转化为string function dataParse(data) if type(data) ~= "table" then return nil end local tmp = {} for key,value in pairs(data) do table.insert(tmp,key .. "=" .. value) end local newData = "" for i = 1,#tmp do newData = newData .. tostring(tmp[i]) if i < #tmp then newData = newData .. "&" end end -- cclog("data:" .. newData) return newData end --------------------------------- -- POST 型,发送数据 function sendInfoToSync() local url = "www.baidu.com" -- 网址 local xhr = cc.XMLHttpRequest:new() xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING xhr.timeout = 30 -- 判断连接超时时间,秒 -- 响应函数 local onReadyFunc = function() if xhr.status ~= -1 then -- 连接成功 local result = xhr.response -- string local cjson = require("cjson") local info = cjson.decode(result) -- json 解析成table else -- 连接失败 end end xhr:registerScriptHandler(onReadyFunc) xhr:open("POST",url) local data = {} data.account = 1 local newData = dataParse(data) xhr:send(newData) end -------------------------------------- -- GET型,获取数据 function loadInfoFromSync() local url = "www.baidu.com" local xhr = cc.XMLHttpRequest:new() xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_JSON xhr.timeout = 30 local onReadyFunc = function() if xhr.status ~= -1 then -- 连接成功 local result = xhr.response -- string local cjson = require("cjson") local info = cjson.decode(result) -- json 解析成table else -- 连接失败 end end xhr:registerScriptHandler(onReadyFunc) local data = {} data.account = 1 local newData = url .. "?" .. dataParse(data) xhr:open("GET",newData) xhr:send() end