-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHTTPRequest.j
80 lines (72 loc) · 2.54 KB
/
HTTPRequest.j
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// (c) 2010-2011 by Anton Korenyushkin
@import "Alert.j"
@implementation HTTPRequest : CPObject
{
JSObject request;
SEL finishAction @accessors;
SEL errorAction @accessors;
SEL errorMessageAction @accessors;
JSObject context @accessors;
CPWindow window @accessors;
}
- (id)initWithMethod:(CPString)method URL:(CPString)url target:(id)target action:(SEL)action // public
{
if (self = [super init]) {
showsAlert = YES;
request = new XMLHttpRequest();
request.open(method, url);
request.onreadystatechange = function () {
if (request.readyState != 4)
return;
var isJSON = request.getResponseHeader("Content-Type") == "application/json; charset=utf-8";
var data = isJSON ? JSON.parse(request.responseText) : request.responseText;
if (finishAction)
objj_msgSend(target, finishAction, data, context);
if (request.status == 200 || request.status == 201) {
if (action)
objj_msgSend(target, action, data, context);
} else if (!errorAction || !objj_msgSend(target, errorAction, data, context)) {
var message, comment;
if (isJSON) {
message = data.message;
comment = data.comment;
} else {
message = data;
}
var alert = [[Alert alloc] initWithMessage:message comment:comment];
if (errorMessageAction) {
[alert setTarget:target];
[alert setAction:errorMessageAction];
}
if (window)
[alert showSheetForWindow:window];
else
[alert showPanel];
}
[[CPRunLoop currentRunLoop] limitDateForMode:CPDefaultRunLoopMode];
};
[self setValue:"XMLHttpRequest" forHeader:"X-Requested-With"];
}
return self;
}
- (id)initWithMethod:(CPString)method URL:(CPString)url // public
{
return [self initWithMethod:method URL:url target:nil action:nil];
}
- (void)setValue:(CPString)value forHeader:(CPString)header // public
{
request.setRequestHeader(header, value);
}
- (void)send:(JSObject)data // public
{
if (data !== nil && typeof(data) != "string" && !(data instanceof DOMFile)) {
[self setValue:"application/json" forHeader:"Content-Type"];
data = JSON.stringify(data);
}
request.send(data || nil);
}
- (void)send // public
{
request.send(nil);
}
@end