我对Ajax的了解有限,我一直在尝试集成到我的rails应用程序中。我希望允许用户能够创建活动并让它们显示在视图中而无需刷新页面。我读到Ajax允许我这样做并按照this指南,我试图将它集成到我的应用程序中。
然而,它似乎没有用,我对于为什么没有任何想法。当用户键入活动名称并单击提交按钮时,我已设法阻止页面刷新,但div部分不会更新以显示新创建的活动,直到用户手动刷新页面为止。
我对Ajax的了解非常有限,所以如果有人能够指出代码有什么问题或它应该是什么,那将是值得赞赏的。
以下是我的视图,控制器和js.erb文件的代码。如果您还需要文件,请与我们联系。
提前致谢
Show.js.erb:
$("#activities").update("<%= escape_javascript(render('activity')) %>");
$("<%= escape_javascript(render @activity) %>").appendTo("#activities");
$('#activities').html("<%= j (render @activity) %>");
Create.js.erb
$("<% escape_javascript(render 'activity')%>").appendTo("#activities");
$('#activities').append('<%= j render(@activity) %>')
活动控制器:
class ActivitiesController < ApplicationController
def display
@activities = Activity.all
@activity = Activity.new
@category = Category.new
@categories = Category.all
end
def index
@activities = Activity.all
@activity = Activity.new
end
def show
@activities = Activity.all
@activity = Activity.new
respond_to do |format|
format.html
format.js
format.json
end
end
def new
@activity = Activity.new
end
def create #Modified all new
@activity = Activity.create(activity_params)
end
def edit
@activity = Activity.find(params[:id])
end
def update
@activity = Activity.update(activity_params)
if @activity.save
flash[:success] = 'Activity successfully updated!'
redirect_to root
else
flash[:error] = 'ERROR: Activity failed to update'
render_to_string
end
end
private
def activity_params
params.require(:activity).permit(:a_name)
end
end
活动显示视图:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script src="jquery.js"></script>
<div class = "row top-buffer text-center">
<div class='col-md-3'>
<h1>
Activities
</h1>
</div>
</div>
<div id="activities">
<% @activities.each do |a| %>
<div>
<h2>
<%= a.a_name %>
</h2>
</div>
<% end %>
</div>
<div>
<%= render 'new' %>
</div>
活动新渲染:
<body>
<% flash.each do |key, value| %>
<div class="alert alert-<%= key %>"><%= value %></div>
<% end %>
<%= form_for @activity, remote: true do |a| %>
<div class = "form-group">
<div class = "row top-buffer text-center">
<div class='col-md-3'>
<%= a.text_field :a_name, id: 'a_name_field', placeholder: 'Activity Name'%>
</div>
</div>
<div class ="row top-buffer text-center">
<div class="col-md-3">
<%= a.submit 'Create', id: 'submitButton', onclick: 'saveActivity()', class: 'btn btn-primary'%>
</div>
</div>
</div>
<% end %>
</body>
答案 0 :(得分:0)
添加此行以确保您的控制器确认js请求:
# activities_controller.rb
class ActivitiesController < ApplicationController
respond_to :html, :js
....
用你的所有create.js.erb代替:
# create.js.erb
$('#activities').html("<%= j (render @activities) %>");
这不是使用追加,而是更简单。它的作用是告诉具有名为“活动”的id的元素再次呈现@activities,其中也应包括新创建的活动记录。
此外,请检查此项以学习用于RoR的AJAX:
https://launchschool.com/blog/the-detailed-guide-on-how-ajax-works-with-ruby-on-rails