itnode / xhr

AJAX web component with no dependencies

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

This is a simple web component that performs AJAX requests for content.

<my-xhr url="https://ron-swanson-quotes.herokuapp.com/v2/quotes"></my-xhr>

(Thanks to jamesseanwright for the mostly unoffensive quote server.)

When added to your pages, this element will go and fetch the content of the specified URL. If the URL changes, it will make a new request. If you specify the credentials attribute/property, then the then AJAX request will be made with credentials.

The result will be availalabe in the response property, and this will emit a response-change event when updated (hint: this matches Polymer's event binding). For example-

var x = document.querySelector('my-xhr');
x.addEventListener('response-change', function() {
  console.info('got response-change, new response', this.response);

  // and e.g., if the response is application/json, containing an array...
  this.response.forEach(function(response) {
    // do something
  });
});

If there was an error making the request, the response property will contain an Error. For example-

var x = document.querySelector('my-xhr');
x.addEventListener('response-change', function() {
  if (x.response instanceof Error) {
    console.warn('got error making XHR', x.response);
  }
});

Supports

Anywhere Custom Elements are supported, including via polyfill.

About

AJAX web component with no dependencies

License:Apache License 2.0


Languages

Language:JavaScript 87.8%Language:HTML 12.2%