Skip to content

Instantly share code, notes, and snippets.

@michaelsbradleyjr
Created July 1, 2013 21:53
Show Gist options
  • Save michaelsbradleyjr/5904969 to your computer and use it in GitHub Desktop.
Save michaelsbradleyjr/5904969 to your computer and use it in GitHub Desktop.
XHR custom element for Google Polymer, adapted to support `responseType` option
<polymer-element name="xhr" attributes="options">
<script src="xhr.js"></script>
<template>
<link rel="stylesheet" href="xhr.css">
</template>
</polymer-element>
<!--
Copyright 2013 The Polymer Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
@host {
* {
display: none !important;
}
}
;(function () {
Polymer("xhr", {
makeReadyStateHandler: function(xhr, callback) {
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback && callback(xhr.response, xhr);
}
};
},
setRequestHeaders: function(xhr, headers) {
if (headers) {
for (var name in headers) {
xhr.setRequestHeader(name, headers[name]);
}
}
},
toQueryString: function(params) {
var r = [];
for (var n in params) {
var v = params[n];
n = encodeURIComponent(n);
r.push(v == null ? n : (n + "=" + encodeURIComponent(v)));
}
return r.join("&");
},
/**
* Sends a HTTP request to the server and returns the XHR object.
*
* @method request
* @param {Object} inOptions
* @param {String} inOptions.url The url to which the request is sent.
* @param {String} inOptions.method The HTTP method to use, default is GET.
* @param {String} inOptions.responseType The desired response type, e.g. "document", "text".
* @param {boolean} inOptions.sync By default, all requests are sent asynchronously.
* To send synchronous requests, set to true.
* @param {Object} inOptions.params Data to be sent to the server.
* @param {Object} inOptions.body The content for the request body for POST method.
* @param {Object} inOptions.headers HTTP request headers.
* @param {Object} inOptions.callback Called when request is completed.
* @returns {Object} XHR object.
*/
request: function(options) {
if (!options) {
options = this.options;
}
var xhr = new XMLHttpRequest();
var url = options.url;
var method = options.method || "GET";
var async = !options.sync;
var params = this.toQueryString(options.params);
var responseType = options.responseType;
if (params && method == "GET") {
url += (url.indexOf("?") > 0 ? "&" : "?") + params;
}
xhr.open(method, url, async);
if (responseType) {
xhr.responseType = responseType;
}
this.makeReadyStateHandler(xhr, options.callback);
this.setRequestHeaders(options.headers);
xhr.send(method == "POST" ? (options.body || params) : null);
if (!async) {
xhr.onreadystatechange(xhr);
}
return xhr;
}
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment