dom_request.js
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
(function() {
function addParamToUrl(url, param) {
return url + (/\?/.test(url) ? '&' : '?') + param;
}
function emptyFn() { }
/**
* Cross-browser abstraction for sending XMLHttpRequest
* @memberOf fabric.util
* @param {String} url URL to send XMLHttpRequest to
* @param {Object} [options] Options object
* @param {String} [options.method="GET"]
* @param {String} [options.parameters] parameters to append to url in GET or in body
* @param {String} [options.body] body to send with POST or PUT request
* @param {Function} options.onComplete Callback to invoke when request is completed
* @return {XMLHttpRequest} request
*/
function request(url, options) {
options || (options = { });
var method = options.method ? options.method.toUpperCase() : 'GET',
onComplete = options.onComplete || function() { },
xhr = new fabric.window.XMLHttpRequest(),
body = options.body || options.parameters;
/** @ignore */
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
onComplete(xhr);
xhr.onreadystatechange = emptyFn;
}
};
if (method === 'GET') {
body = null;
if (typeof options.parameters === 'string') {
url = addParamToUrl(url, options.parameters);
}
}
xhr.open(method, url, true);
if (method === 'POST' || method === 'PUT') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhr.send(body);
return xhr;
}
fabric.util.request = request;
})();