-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathajax.coffee
More file actions
88 lines (72 loc) · 1.94 KB
/
ajax.coffee
File metadata and controls
88 lines (72 loc) · 1.94 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
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
81
82
83
84
85
86
87
MIME_TYPES =
json: 'application/json'
html: 'text/html'
@ajax = (options) ->
applyDefaults(options)
serializeData(options)
abortController = new AbortController()
timer = setTimeout =>
abortController.abort()
, options.timeout * 1000
fetch(
options.url,
headers: processHeaders(options)
method: options.type
contentType: options.dataType
signal: abortController.signal
).then((response) ->
if options.dataType == 'json'
response.json()
else
response.text()
).then((data) ->
if data?
onSuccess data, options
else
onError 'invalid', '', options
).catch((error) ->
onError 'error', error, options
).finally ->
clearTimeout timer
ajax.defaults =
async: true
dataType: 'json'
timeout: 30
type: 'GET'
# contentType
# context
# data
# error
# headers
# progress
# success
# url
applyDefaults = (options) ->
for key of ajax.defaults
options[key] ?= ajax.defaults[key]
return
serializeData = (options) ->
return unless options.data
if options.type is 'GET'
options.url += '?' + serializeParams(options.data)
options.data = null
else
options.data = serializeParams(options.data)
return
serializeParams = (params) ->
("#{encodeURIComponent key}=#{encodeURIComponent value}" for key, value of params).join '&'
processHeaders = (options) ->
options.headers or= {}
if options.contentType
options.headers['Content-Type'] = options.contentType
if not options.headers['Content-Type'] and options.data and options.type isnt 'GET'
options.headers['Content-Type'] = 'application/x-www-form-urlencoded'
if options.dataType
options.headers['Accept'] = MIME_TYPES[options.dataType] or options.dataType
return options.headers
onSuccess = (data, options) ->
options.success?.call options.context, data, options
return
onError = (type, error, options) ->
options.error?.call options.context, type, error, options
return