|
1
|
|
|
/** global: GLSR, XMLHttpRequest */ |
|
2
|
|
|
;(function() { |
|
3
|
|
|
|
|
4
|
|
|
'use strict'; |
|
5
|
|
|
|
|
6
|
|
|
GLSR.Ajax = function() { |
|
7
|
|
|
/** @return void */ |
|
8
|
|
|
this.get = function( url, successCallback ) { |
|
9
|
|
|
var xhr = new XMLHttpRequest(); |
|
10
|
|
|
xhr.open( 'GET', url ); |
|
11
|
|
|
xhr.onreadystatechange = function() { |
|
12
|
|
|
if( xhr.readyState !== 4 )return; |
|
13
|
|
|
successCallback( xhr.responseText ); |
|
14
|
|
|
}; |
|
15
|
|
|
xhr.setRequestHeader( 'X-Requested-With', 'XMLHttpRequest' ); |
|
16
|
|
|
xhr.send(); |
|
17
|
|
|
}; |
|
18
|
|
|
|
|
19
|
|
|
/** @return bool */ |
|
20
|
|
|
this.isFileAPISupported = function() { |
|
21
|
|
|
var input = document.createElement( 'INPUT' ); |
|
22
|
|
|
input.type = 'file'; |
|
23
|
|
|
return 'files' in input; |
|
24
|
|
|
}; |
|
25
|
|
|
|
|
26
|
|
|
/** @return bool */ |
|
27
|
|
|
this.isFormDataSupported = function() { |
|
28
|
|
|
return !!window.FormData; |
|
29
|
|
|
}; |
|
30
|
|
|
|
|
31
|
|
|
/** @return bool */ |
|
32
|
|
|
this.isUploadSupported = function() { |
|
33
|
|
|
var xhr = new XMLHttpRequest(); |
|
34
|
|
|
return !!( xhr && ( 'upload' in xhr ) && ( 'onprogress' in xhr.upload )); |
|
35
|
|
|
}; |
|
36
|
|
|
|
|
37
|
|
|
/** @return void */ |
|
38
|
|
|
this.post = function( data, successCallback, headers ) { |
|
39
|
|
|
var xhr = new XMLHttpRequest(); |
|
40
|
|
|
this.setHeaders_( xhr, headers ); |
|
41
|
|
|
xhr.open( 'POST', GLSR.ajaxurl ); |
|
42
|
|
|
xhr.onreadystatechange = function() { |
|
43
|
|
|
if( xhr.readyState !== 4 )return; |
|
44
|
|
|
successCallback( JSON.parse( xhr.responseText )); |
|
45
|
|
|
}; |
|
46
|
|
|
xhr.send({ |
|
47
|
|
|
action: GLSR.action, |
|
48
|
|
|
request: data, |
|
49
|
|
|
}); |
|
50
|
|
|
}; |
|
51
|
|
|
|
|
52
|
|
|
/** @return void */ |
|
53
|
|
|
this.setHeaders_ = function( xhr, headers ) { |
|
54
|
|
|
headers = headers || {}; |
|
55
|
|
|
headers['X-Requested-With'] = 'XMLHttpRequest'; |
|
56
|
|
|
for( var key in headers ) { |
|
|
|
|
|
|
57
|
|
|
xhr.setRequestHeader( key, headers[key] ); |
|
58
|
|
|
} |
|
59
|
|
|
}; |
|
60
|
|
|
}; |
|
61
|
|
|
})(); |
|
62
|
|
|
|
When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically: