Ajax(Asynchronous JavaScript and XML)是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。在Ruby on Rails中,使用Ajax可以提供更流畅的用户体验,因为它允许应用程序异步地与服务器通信并更新页面内容。
以下是一个简单的例子,展示了如何在Ruby on Rails中使用jQuery Ajax来呈现对象。
class ItemsController < ApplicationController
def index
@items = Item.all
respond_to do |format|
format.html
format.json { render json: @items }
end
end
end
<div id="items">
<%= render @items %>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#items').on('click', '.load-more', function() {
$.ajax({
url: '/items',
type: 'GET',
dataType: 'json',
success: function(data) {
$.each(data, function(index, item) {
$('#items').append('<div>' + item.name + '</div>');
});
},
error: function(xhr, status, error) {
console.error('An error occurred: ' + error);
}
});
});
});
</script>
<div><%= item.name %></div>
protect_from_forgery
方法,并确保Ajax请求包含正确的CSRF令牌。通过以上信息,你应该能够在Ruby on Rails中成功使用Ajax来呈现对象,并解决可能遇到的常见问题。
没有搜到相关的文章