Rails:提交表单而不重新加载页面

我的应用程序( https://showthatview.herokuapp.com/ )包含两部分:

  • Google地球窗格,其中显示视图
  • 一种forms,用户在其中设置他想要设置相机的地址/高度

当用户提交表单时,我希望RoR后端存储用户设置的参数,并希望JS前端更新视图。 我得到了两个独立的部分。

当用户提交Rail表单时,它会重新加载页面并“重置”相机

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

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

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

应用程序/资产/视图/ google_earth / index.html.erb

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

在您的路线文件中:

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

应用程序/资产/视图/ 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

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

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

使用jQuery:

 $("button").click(function(){ $.ajax({url: "/get_some_route/", success: function(result){ $("#div1").html(result); }}); }); 

使用Rails:

xxx.html.erb

 <%= link_to 'Daily Collection', 'daily_collection', class: "btn btn-info", method: 'get', remote: true %> 

的routes.rb

 get 'daily_collection' => 'patients#daily_collection' 

patients_controller.rb

 class Patients def daily_collection do something... end end 

collection_money.html.erb

 

to be appended with the called page

daily_collection.js.erb

 $('#price_daily').html('<%= escape_javascript(render :partial => 'collection_money') %>'); 

以供参考:

  • 导轨指南
  • jQuery Ajax
Interesting Posts