Use GitHub's fetch library with Ruby on Rails. Based heavily on this wrapper to encapsulate some of the callback handling of HTTP status codes.
- Make sure you have the fetch library added to your
app.jsmanifest file. - Ensure your root layout file (usually called
app/views/layouts/application.html.erb) has<%= csrf_meta_tags %>within the<head>tag. - Copy the
fetch-rails.jsto your/vendor/assets/javascripts/folder. - Add
//= require fetch-railsdirectly below where you have added the fetch library to yourapp.jsmanifest.
Fetch.html( '/api/web/get-html' )
.then( function( response ){
document.body.innerHTML = response.data;
});// endpoint returns { name: 'Adam', age: 30 }
Fetch.json( '/api/web/get-json' )
.then( function( data ){
this.name = data.name;
this.age = data.age;
});Fetch.text( '/api/web/get-text' )
.then( function( text ){
document.querySelector( '.item' ).innerText = text;
});Fetch.post( '/api/web/submit-form', 'form.my-form' )
.then( function( response ){
document.querySelector( '.alert' ).innerText = 'Form submitted!';
}).catch( function( error ){
document.querySelector( '.alert' ).innerText = error;
});Fetch.post( '/api/web/submit-form', 'form.my-form', 'input.file-uploader' )
.then( function( response ){
document.querySelector( '.alert' ).innerText = 'File uploaded!';
}).catch( function( error ){
document.querySelector( '.alert' ).innerText = error;
});Fetch.postJSON( '/api/web/post-json', { name: 'Adam', age: 30 } )
.then( function( response ){
document.querySelector( '.alert' ).innerText = 'JSON submitted!';
}).catch( function( error ){
document.querySelector( '.alert' ).innerText = error;
});- Rails 4.0+
- Chrome latest
- Safari latest
- Firefox latest
- Opera latest
- IE 9+
- Safari mobile latest
- Chrome mobile latest