Rails 3 / jquery / ajax - can i change this to submit one answer instead of the entire form?

戏子无情 提交于 2019-12-25 17:03:10

问题


I'm grateful to the folks who helped me meander my way through a diagnostic process here. I rewrote the code that i am hoping will continue to work through future versions of jQuery.

I am concerned, though, about two things:

  1. Have i coded something else that is going to come back and bite me in the tail?
  2. Quite a few clients complete part of the questions, close the browser and expect their work to be there when they came back to finish. So the entire form is submitted every time a radio button is clicked (100+ records). I wondered about the possibility of creating a form for each question here and received no responses. Is there some way to submit one answer at a time instead of the whole form?

view:

    <%= form_tag update_result_answers_path, :remote => true do %>
    <% @answers.each do |q| %>
        <tr>
            <td><%= q[0].question %></td>
            <% [ 1, 2, 3, 4, 5 ].each do |f| %>
                <% if f == q[1].score
                    chk="checked='checked'"
                else
                    chk=""
                end %>
                <td>
                    <input "<%= chk %>" class="submittable" name="answer[<%=q[1].id%>]" type="radio" value="<%= f %>" />
                </td>
            <% end %>
        </tr>
    <% end %>
    <% end %>

application.js:

$('.submittable').live('change', function() {
        $(this).parents('form:first').submit();
        return false;
        }
    );

controller:

  def update_result
    params[:answer].each_pair do |key,value|
      @ans = Answer.find(key.to_i)
      @ans.update_attributes(:score => value)
    end
  end

_index.js.erb:

$("#answers").html("<%=escape_javascript(render(@answers)) %>");

Thank you!


回答1:


I would keep your view as it is, and change the application.js, to be as little obtrusive as possible :

$('.submittable').live('change', function() {
  $.post(
    $(this).closest('form').attr('href'),
    $(this).serialize()
  );
});

EDIT : I didn't see that you want to render the answers afterwards. I'm not sure how to avoid code duplication with this solution then...



来源:https://stackoverflow.com/questions/6201964/rails-3-jquery-ajax-can-i-change-this-to-submit-one-answer-instead-of-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!