[英]How to submit form and update element on the page without refresh, in Rails 4
我在尝试做一些我认为相当简单的事情时遇到了很多麻烦。
我有一个项目清单,比如说,待办事项。 在该列表的底部,我有一个文本字段,我可以在其中向该列表添加新项目。 我想让它动态地将新项目添加到该列表的底部,而不像在聊天窗口中那样刷新整页。
我将提交表单设置为remote: true
并且它在不重新加载页面的情况下成功提交,但我无法同时让新项目出现在列表底部。 我必须刷新页面才能看到更改。
我尝试了在 SO 上找到的几种不同方法(这里不乏类似的问题)和网络,甚至是一个名为 Sync 的 gem,但它们每个都有自己的错误和问题,我无法解决任何问题适当地。 他们每个人都可以是它自己的 SO 问题。 所以我问:是否有一个“食谱”可以确保在 Rails 4 中成功实现这一点?
比方说,现在你有一个用户表单要提交,
<%=form_for @user,remote: true%><%end%>
你还有一个控制器,
UsersController
在您的控制器中,您有一个功能,
def create
#something
end
这是表格。
您唯一需要做的就是修改函数,例如
def create
#something
respond_to do |format|
format.js
format.html
end
end
然后在您的视图端,在 view/users/ 目录下,创建一个 create.js 文件,在该文件中,您可以执行 js 操作,例如获取新记录,并将新记录附加到用户列表中。
参考:
http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#form-for
有多种方法可以完成您的要求。 我的方法是:
创建对传递表单参数的控制器的AJAX
调用
在控制器内部,您保存/更新内容,然后返回一个JSON
对象
在AJAX
函数的success
回调中,您使用对象值附加一个列表项/表行
代码可能是这样的:
模型.js
$(function() {
$("#submit_button").on("click", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "your_controller_url",
data: "your_form_data"
success: function(result) {
// Append the result to a table or list, $("list").append(result)
},
});
});
});
控制器文件
def your_action
# Do your stuff
# return JSON to the ajax call
end
好吧,这只是一个骨架。 我更喜欢以这种方式做事。 (因为我讨厌 js.erb 方法)
这是 rails 5,希望它会帮助某人(它仍然适用于 rails 4):
试试这个 ajax 示例:
在“routes.rb”中:
# set the route that ajax can find the path to what controller in backend
get '/admin/some_great_flow', to: 'great_control#great_flow'
在“great_control_controller.rb”控制器中:
# this function in controller will response for ajax's call
def great_flow
# We can find some user or getting some data, model here.
# 'params[:id]' is passed by ajax that we can use it to find something we want.
@user = User.find(params[:id])
# print whole data on terminal to check it correct.
puts YAML::dump(@user.id)
# transform what you want to json and pass it back.
render json: {staff_info: @user }
end
在“app/views/great_control/index.html.erb”视图中:
<div>
<label>Staffs</label>
<%=select_tag(:staff, options_from_collection_for_select(@staffs, :id, :name), id:"staff_id", required: true)%>
</div>
<script>
//every time if option change it will call ajax once to get the backend data.
$("#staff_id").change(function(event) {
let staff_id = $("#staff_id").val()
$.ajax({
// If you want to find url can try this 'localhost:prot/rails/info/routes'
url: '/admin/some_great_flow',
type: 'GET',
dataType: 'script',
data: { id: staff_id },
// we get the controller pass here
success: function(result) {
var result = JSON.parse(result);
console.log(result['staff_info']);
// use the data from backend for your great javascript.
},
});
});
</script>
我是为自己写的。
您可以使用 javascript 查看更改。 例如,让我们考虑一个带有操作索引的控制器 Mycontroller 并且您正在提交表单上的索引。 然后在视图 my_controller/index.js.erb 中创建一个文件
要反映更改,请在此模板中使用 javascript。 肯定是远程发送 ajax 调用,因此要查看更改,您需要使用 javascript 进行一些操作。
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.