6 * Sends a HTTP request to the server and returns the XHR object.
9 * @param {Object} inOptions
10 * @param {String} inOptions.url The url to which the request is sent.
11 * @param {String} inOptions.method The HTTP method to use, default is GET.
12 * @param {boolean} inOptions.sync By default, all requests are sent asynchronously. To send synchronous requests, set to true.
13 * @param {Object} inOptions.params Data to be sent to the server.
14 * @param {Object} inOptions.body The content for the request body for POST method.
15 * @param {Object} inOptions.headers HTTP request headers.
16 * @param {String} inOptions.responseType The response type. Default is 'text'.
17 * @param {boolean} inOptions.withCredentials Whether or not to send credentials on the request. Default is false.
18 * @param {Object} inOptions.callback Called when request is completed.
19 * @returns {Object} XHR object.
21 request: function(options) {
22 var xhr = new XMLHttpRequest();
23 var url = options.url;
24 var method = options.method || 'GET';
25 var async = !options.sync;
27 var params = this.toQueryString(options.params);
28 if (params && method == 'GET') {
29 url += (url.indexOf('?') > 0 ? '&' : '?') + params;
31 var xhrParams = this.isBodyMethod(method) ? (options.body || params) : null;
33 xhr.open(method, url, async);
34 if (options.responseType) {
35 xhr.responseType = options.responseType;
37 if (options.withCredentials) {
38 xhr.withCredentials = true;
40 this.makeReadyStateHandler(xhr, options.callback);
41 this.setRequestHeaders(xhr, options.headers);
44 xhr.onreadystatechange(xhr);
49 toQueryString: function(params) {
51 for (var n in params) {
53 n = encodeURIComponent(n);
54 r.push(v == null ? n : (n + '=' + encodeURIComponent(v)));
59 isBodyMethod: function(method) {
60 return this.bodyMethods[(method || '').toUpperCase()];
70 makeReadyStateHandler: function(xhr, callback) {
71 xhr.onreadystatechange = function() {
72 if (xhr.readyState == 4) {
73 callback && callback.call(null, xhr.response, xhr);
78 setRequestHeaders: function(xhr, headers) {
80 for (var name in headers) {
81 xhr.setRequestHeader(name, headers[name]);