Rails: submitting a form without reloading the pag

2019-04-02 18:30发布

问题:

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

  • A Google Earth pane, where a view is shown
  • A form, where the user sets the address / height where he wants the camera to be set

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.

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?

回答1:

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.

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

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

In your routes file:

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 }) %>");

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


回答2:

With jQuery:

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

With 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') %>');

for more reference:

  • Rails Guide
  • jQuery Ajax