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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。