MyHttpRequest.lua
1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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