score.ajax

A small helper for managing AJAX requests.

Quickstart

<script src="score.init.js"></script>
<script src="score.ajax.js"></script>
<script>
    score.ajax('/api/fruits').then(function(result) {
        for (var i = 0; i < result.length; i++) {
            console.log('Initiating self-defense against ' + result[i]);
        }
    });
</script>

Details

Return value

The return value of this function depends on the Content-Type header of the server response. You can find a good documentation of the XMLHttpRequest.response types on MDN.

Callback

Internet explorer does not provide promises, you will either have to use a polyfill, or use the callback-based API of this module:

score.ajax.callback('/api/fruits', function(result) {
    for (var i = 0; i < result.length; i++) {
        console.log('Initiating self-defense against ' + result[i]);
    }
}, function() {
    // this is the error callback
    alert('Could not load fruits, nothing to defend against!');
});

If you are passing any options, you must provide them before the callback:

score.ajax.callback('/api/fruits', {headers: {'X-Spam': 'spam!'}}, function(result) {
    ...

Options

You can pass an options object after the URL. The following keys are currently supported:

  • method: An HTTP verb to use (i.e. “POST”, “PUT”, etc.) Defaults to “GET”.
  • data: The body of the request. Can be anything accepted by XMLHttpRequest.send()
  • headers: An object mapping HTTP headers to values. These will be sent as part of the request. Note that you cannot set certain headers (you can find the list of forbidden headers on MDN). Also note, that it is also possible to perform cross-domain AJAX requests, albeit with heavy restrictions.
  • crossDomain: By default the ‘X-Requested-With’: ‘XMLHttpRequest’ header will always be set. Setting this value to true will override that behaviour.