behavior layer) from a Web page's structure/content and presentation)
data-*
属性关联local: false
| remote: true
-> data-remote='true'
data-url , data-params, data-method, data-type
data: {confirm: "Are your sure?"}
-> data-confirm
data: {disable_with: "Saving..."}
-> data-disable-with
Rails-ujs event handlers
event
. In this parameter, there is an additional attribute detail
which contains an array of extra parameters.document.body.addEventListener("ajax:success", (event) => {
const [data, status, xhr] = event.detail;
});
Event name | Extra parameters (event.detail) | Fired |
---|---|---|
ajax:before | Before the whole ajax business. | |
ajax:beforeSend | [xhr, options] | Before the request is sent. |
ajax:send | [xhr] | When the request is sent. |
ajax:stopped | When the request is stopped. | |
ajax:success | [response, status, xhr] | After completion, if the response was a success. |
ajax:error | [response, status, xhr] | After completion, if the response was an error. |
ajax:complete | [xhr, status] | After the request has been completed, no matter the outcome. |
falseattribute to the tag
<a href="..." data-turbolinks="false">No turbolinks here</a>.
load
-> turbolinks:load
document.addEventListener("turbolinks:load", () => {
alert("page has loaded!");
});
Server side
// foo.js.erb
var users = document.querySelector("#users");
users.insertAdjacentHTML("beforeend", "<%= j render(@user) %>");
// JS style
$.get( "/vegetables", function(data) {
alert("Vegetables are good for you!");
});
// Rails style
Rails.ajax({
url: "/books",
type: "get",
data: "",
success: function(data) {},
error: function(data) {}
})
Server side
// Javascript view example:
Rails.$('.random-number')[0].innerHTML = ("<%= j (render partial: 'random') %>")
// jQuery example:
$('.random-number').html("<%= j (render partial: 'random') %>")
// `j` is an alias for `escape_javascript`
# controller
render json: { html: render_to_string(partial: 'random') }
# client JS
Rails.ajax({
url: "/books",
type: "get",
success: function(data) { Rails.$(".random-number")[0].innerHTML = data.html; }
})
Hide Load More buttons when all items have been rendered in Ruby on Rails