MyHttpRequest.lua 1.53 KB
cc.exports.MyHttpRequest = class("MyHttpRequest")

local dkjson = require("core.net.dkjson");

function MyHttpRequest:getInstance()
    local myHttpRequest = _G.myHttpRequest
    if myHttpRequest then
        return myHttpRequest
	end

    myHttpRequest = MyHttpRequest.new()
    cc.exports.myHttpRequest = myHttpRequest;
    setmetatable(myHttpRequest, self);
	self.__index = self;
    return myHttpRequest;
end

function MyHttpRequest:ctor()
    
end

--Http请求
function MyHttpRequest:request(type,uri,header,params,callBack)
    local xhr = cc.XMLHttpRequest:new()
    xhr.responseType = 4;
    xhr:open(type, uri);

   xhr:setRequestHeader("Content-Type","application/x-www-form-urlencoded")
   local Authorization = "MyAuth "..header;
   xhr:setRequestHeader("Authorization",Authorization)    -- 提交的参数

    local function onReadyStateChange()
        if xhr.readyState == 4 and (xhr.status >= 200 and xhr.status < 207) then
            print("[MyHttpRequest].URI:"..uri);
            print("[MyHttpRequest].response:"..xhr.response);
            local obj = dkjson.decode(xhr.response);
            if callBack then
                callBack(obj);
            end
        else
            print("xhr.readyState is:", xhr.readyState, "xhr.status is: ",xhr.status)
        end
        xhr:unregisterScriptHandler();
    end
    xhr:registerScriptHandler(onReadyStateChange);
--    LuajUtil.luaPrint("MyHttpRequest Params:"..params,0);
    if params ~= "" then
        xhr:send(params);
    else
        xhr:send();
    end
end

return MyHttpRequest