【问题标题】:Rails: submitting a form without reloading the pageRails:提交表单而不重新加载页面
【发布时间】:2014-12-06 14:53:17
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 不在这里 - 你的意思是我应该?
  • @FrancescoBovoli 他的意思是,你发送 ajax 请求很热吗?
  • 添加 remote: true 应该可以解决问题。

标签: javascript ruby-on-rails ruby-on-rails-4 google-earth


【解决方案1】:

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

此外,您需要在控制器中创建一个新方法来转发响应您的提交,并在您的视图文件夹(可能是 js.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

$('#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

【讨论】:

  • 是的,remote:true 是我所缺少的。在我在这里找到的 Rails 文档中也有解释(在你把我放在正确的机架上之后):edgeguides.rubyonrails.org/…
【解决方案2】:

使用 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

<p>to be appended with the called page </p>

daily_collection.js.erb

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

更多参考:

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 2013-10-14
    • 2017-09-19
    • 1970-01-01
    • 2017-06-23
    相关资源
    最近更新 更多