-
Notifications
You must be signed in to change notification settings - Fork 1
/
httpRequest.js
69 lines (66 loc) · 2.06 KB
/
httpRequest.js
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
/**
* @description make a simple http request
* @param {string} method
* @param {string} url
* @param {Object} param
* @return {void}
* independent
*/
function httpRequest(method, url, param) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
method = method.toLowerCase();
if (method == 'get') {
// convert param to ?key1=value1&key2=value2
var temp = '';
if (param) {
for (var key in param) {
temp += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(param[key]);
}
if (temp.length) {
temp = temp.replace(/^&/, '?');
if (url[url.lastIndexOf('/') - 1] == '/') url += '/';
url += temp;
}
}
param = null;
} else if (method == 'post') {
param = JSON.stringify(param);
}
xhr.open(method, url, true);
if (method == 'post') {
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
}
xhr.onload = function() {
if (this.status == 200 || this.status == 304) {
return resolve(this.response);
} else {
return reject(true);
}
}
xhr.onerror = function() {
return reject(true);
}
xhr.send(param);
});
}
(function exportModuleUniversally(root, factory) {
if (typeof(exports) === 'object' && typeof(module) === 'object')
module.exports = factory();
else if (typeof(define) === 'function' && define.amd)
define(factory);
/* amd // module name: diff
define([other dependent modules, ...], function(other dependent modules, ...)) {
return exported object;
});
usage: require([required modules, ...], function(required modules, ...) {
// codes using required modules
});
*/
else if (typeof(exports) === 'object')
exports['httpRequest'] = factory();
else
root['httpRequest'] = factory();
})(this, function factory() {
return httpRequest;
});