1 2 3 Polymer('core-xhr', { 4 5 /** 6 * Sends a HTTP request to the server and returns the XHR object. 7 * 8 * @method request 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. 20 */ 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; 26 // 27 var params = this.toQueryString(options.params); 28 if (params && method == 'GET') { 29 url += (url.indexOf('?') > 0 ? '&' : '?') + params; 30 } 31 var xhrParams = this.isBodyMethod(method) ? (options.body || params) : null; 32 // 33 xhr.open(method, url, async); 34 if (options.responseType) { 35 xhr.responseType = options.responseType; 36 } 37 if (options.withCredentials) { 38 xhr.withCredentials = true; 39 } 40 this.makeReadyStateHandler(xhr, options.callback); 41 this.setRequestHeaders(xhr, options.headers); 42 xhr.send(xhrParams); 43 if (!async) { 44 xhr.onreadystatechange(xhr); 45 } 46 return xhr; 47 }, 48 49 toQueryString: function(params) { 50 var r = []; 51 for (var n in params) { 52 var v = params[n]; 53 n = encodeURIComponent(n); 54 r.push(v == null ? n : (n + '=' + encodeURIComponent(v))); 55 } 56 return r.join('&'); 57 }, 58 59 isBodyMethod: function(method) { 60 return this.bodyMethods[(method || '').toUpperCase()]; 61 }, 62 63 bodyMethods: { 64 POST: 1, 65 PUT: 1, 66 DELETE: 1 67 }, 68 69 makeReadyStateHandler: function(xhr, callback) { 70 xhr.onreadystatechange = function() { 71 if (xhr.readyState == 4) { 72 callback && callback.call(null, xhr.response, xhr); 73 } 74 }; 75 }, 76 77 setRequestHeaders: function(xhr, headers) { 78 if (headers) { 79 for (var name in headers) { 80 xhr.setRequestHeader(name, headers[name]); 81 } 82 } 83 } 84 85 }); 86 87