Rails:提交表单而不重新加载页面 [英] Rails: submitting a form without reloading the page

查看:40
本文介绍了Rails:提交表单而不重新加载页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用(https://showthatview.herokuapp.com/)有两部分:

My app (https://showthatview.herokuapp.com/) has two parts:

  • Google 地球窗格,其中显示了视图
  • 一个表单,用户可以在其中设置他想要设置相机的地址/高度

当用户提交表单时,我想让RoR后端存储用户设置的参数,JS前端更新视图.我让两个独立的部分正常工作.

When the user submits the form, I want the RoR back end to store the parameters set by the user, and the JS front end to update the view. I got the two separate parts working.

当用户提交 Rail 表单时,它会重新加载页面并重置"摄像头

When the user submits the Rail forms, it reloads the page and "resets" the camera

理想情况下,我希望表单在不重新加载页面的情况下将数据提交到后端 - 这可能吗?或者也许我这样做完全错误?

Ideally I want the form to submit the data to the back end without reloading the page - is this possible? Or maybe I'm doing this completely wrong?

推荐答案

发布一些代码会有所帮助,但请尝试在表单中添加remote: true".这将告诉您的页面在提交时不要刷新.

Posting some of your code would help, but try adding "remote: true" to your form. That will tell your page not to refresh upon submitting.

此外,您需要在控制器中创建一个新方法来转发响应您的提交和视图文件夹(可能是一个 js.erb 文件)中的一个页面来重新加载数据.没有看到您的代码,步骤的快速示例:

Furthermore, you will need to create a new method in your controller to forward to that responds to your submission and a page in your views folder (probably a js.erb file) that reloads the data. Without seeing your code, a quick example of the steps:

app/assets/views/google_earth/index.html.erb

app/assets/views/google_earth/index.html.erb

<%= form_for(@pane_view, url: camera_path, remote: true) do |f|%>

在你的路由文件中:

get 'camera' => 'google_earth#cameraUpdate', as: 'camera'

app/assets/views/google_earth/camera.js.erb

app/assets/views/google_earth/camera.js.erb

$('#camera-pane').html("<%= escape_javascript(render partial: 'camera_view', :locals => { x_coord: @x, y_coord: @y }) %>");

这假设您的窗格有部分视图,如果您还没有,我建议将其作为部分视图:app/assets/views/google_earth/_camera_view.html.erb

This is assuming you have a partial view for your pane, I recommend doing it as a partial if you haven't already: app/assets/views/google_earth/_camera_view.html.erb

最后,您需要在控制器中:

Finally, in your controller you will want:

def cameraUpdate
  @x = params[:x_coordinate]
  @y = params[:y_coordinate]
  respond_to do |format|
    format.html
    format.js
  end
end

这篇关于Rails:提交表单而不重新加载页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆