cocos-lua超文本传输协议(http)数据通信方式

function ExchangeLayer:requestDhRecoreData()
    self:onHttpJsionTable(url .. "/WS/MobileInterface.ashx","GET","action=getFriendlist&userid="..GlobalUserItem.dwUserID,
        function(jstable,jsdata)
 
        if type(jstable) == "table" then

        end
    end)
end

--HTTP获取json
function ExchangeLayer.onHttpJsionTable(url,methon,params,callback)
    
    local xhr = cc.XMLHttpRequest:new() --创建请求
    xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_JSON--返回数据类型为json
    local bPost = ((methon == "POST") or (methon == "post"))

    --模式判断
    if not bPost then
        if params ~= nil and params ~= "" then
            xhr:open(methon, url.."?"..params)
            print("HTTP获取json appdf.onHttpJsionTable:"..url.."?"..params)
        else
            xhr:open(methon, url)
            print("HTTP获取json appdf.onHttpJsionTable:"..url)
        end
    else
        xhr:open(methon, url)
    end
    --HTTP回调函数
    local function onJsionTable()
        local datatable 
        local response
        local ok
        if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
               response  = xhr.response -- 获得响应数据
               if response then
                   ok, datatable = pcall(function()
                   return cjson.decode(response)
                end)
                if not ok then
                    print("onHttpJsionTable_cjson_error")
                    datatable = nil
                end
            end
        else
            print("onJsionTable http fail readyState:"..xhr.readyState.."#status:"..xhr.status)
        end
        if type(callback) == "function" then      
            callback(datatable,response)         --pcall在保护模式(protected mode)下执行函数内容,同时捕获所有的异常和错误。若一切正常,pcall返回true以及“被执行函数”的返回值;否则返回nil和错误信息。
        end        
    end
    xhr:registerScriptHandler(onJsionTable) --注册响应函数
    if not bPost then
        xhr:send() --发送请求
    else
        xhr:send(params)
    end
    return true
end

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值