cocos2dx 网络连接


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值