your programing

ajax 방식으로 레일 3에 양식 제출 (jQuery 사용)

lovepro 2020. 10. 13. 08:19
반응형

ajax 방식으로 레일 3에 양식 제출 (jQuery 사용)


저는 rails와 jQuery의 초보자입니다. 한 페이지에 두 개의 별도 양식이 있으며 jQuery를 사용하여 ajax 방식으로 별도로 제출하고 싶습니다. 이것이 내가 얼마나 멀리 왔는지입니다. 누구나이 코드를 추가하거나 수정할 수 있습니다. Rails 3.1과 jQuery 1.6을 사용하고 있습니다. 미리 감사드립니다.

application.js

$(".savebutton").click(function() { 
    $('form').submit(function() {
         $(this).serialize();
    });
}); 

첫 번째 형태 :

<%=form_for :users do |f| %>
  <fieldset>
    <legend>Basic details</legend>
    <%= f.label :school %>
    <%= f.text_field :school,:size=>"45",:class=>"round",:id=>"school" %><br/>      
  </fieldset>
  <p><%= button_to "save and continue",{:class=>"savebutton"} %></p>
<%end%>

두 번째 형태 :

<%=form_for :courses do |c| %>
  <fieldset>
    <legend>Your current classes</legend>
    <label>class:</label><%= c.text_field :subject,:size=>"45",:class=>"round" %><br/>
  </fieldset>
  <p><%= button_to "save and continue",{:class=>"savebutton"} %></p>
<%end%>

SchoolController

class SchoolController < ApplicationController
  respond_to :json
  def create
    @school = current_user.posts.build(params[:school].merge(:user => current_user))
    if @school.save
      respond_with @school
    else
      respond_with @school.errors, :status => :unprocessable_entity
    end
  end
end

CourseController는 SchoolController와 같은 모양입니다.


당신이 원하는 :

  1. 제출의 정상적인 동작을 중지하십시오.
  2. ajax를 통해 서버로 보냅니다.
  3. 답장을 받고 그에 따라 변경하십시오.

아래 코드는이를 수행해야합니다.

$('form').submit(function() {  
    var valuesToSubmit = $(this).serialize();
    $.ajax({
        type: "POST",
        url: $(this).attr('action'), //sumbits it to the given url of the form
        data: valuesToSubmit,
        dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
    }).success(function(json){
        console.log("success", json);
    });
    return false; // prevents normal behaviour
});

:remote => true양식에 사용 하는 경우 JavaScript로 제출할 수 있습니다.

$('form#myForm').trigger('submit.rails');

Rails 3에서 ajax 양식 제출을 수행하기 위해 선호하는 방법은 Rails-ujs를 활용하는 것입니다.

기본적으로 Rails-ujs가 ajax 제출을 수행하도록 허용합니다 (그리고 js 코드를 작성할 필요가 없습니다). 그런 다음 js 코드를 작성하여 응답 이벤트 (또는 기타 이벤트)를 캡처하고 작업을 수행합니다.

다음은 몇 가지 코드입니다.

먼저 form_for 에서 원격 옵션을 사용하여 양식이 기본적으로 ajax를 통해 제출되도록합니다.

form_for :users, remote:true do |f|

그런 다음 ajax 응답 상태 (예 : 성공한 응답)에 따라 일부 작업을 수행하려면 다음과 같이 javscript 논리를 작성합니다.

$('#your_form').on('ajax:success', function(event, data, status, xhr) {
  // Do your thing, data will be the response
});

가 있습니다 여러 이벤트 당신이 연결할 수 있습니다.


To submit form via AJAX you could just pass :remote => true to the form_for helper. By default rails 3.0.x uses prototype js lib, but you can change it to jquery with the jquery-rails gem (which is the default for rails 3.1). bundle install it and then rails g jquery:install to replace the prototype files with jquery.

After that you'll just need to handle the callback. Take a look at this screencast


it's very important in your request with ajax stop the beahavior default, send remote:true in your form_for

<%= form_for :session, url: sessions_path, remote: true, html: { class: "form-signin" } do |f| %>

<% end %>

in your ajax

$(".form-signin").on("submit", function(e) {
    $.ajax({
        url: $(this).attr('action'),
        data: $(this).serialize(),
        type: "POST",
        dataType: "json",
        success: function(response) {
            console.log(response)
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
    e.preventDefault(); //THIS IS VERY IMPORTANT
});

Nothing here worked for me, my issue was the jQuery modal library would break my forms from being submitted via remote data if I brought up a modal window, but I found a fix.

First add the jQuery Form Plugin to your assets javascript directory: http://malsup.github.io/jquery.form.js

Now override the submit method for your form. For example you could do something like this:

= form_for @object, html: {class: "ajax_form_submit"}, authorization_token: true do |f|
  = f.text_input

javascript:

  $(document).on('ready page:load', function() {

    $(".ajax_form_submit").submit(function () {
      var form = $(this)
      form.ajaxSubmit({
        success: function (responseText, statusText, xhr) {
          console.log('success: ajax_form_submit')
        },
        error: function (jqXHR, statusText, errorThrown) {
          console.log('error: ajax_form_submit');
          console.log(jqXHR, statusText, errorThrown);
        }
      })
    })

  })

참고URL : https://stackoverflow.com/questions/6723334/submit-form-in-rails-3-in-an-ajax-way-with-jquery

반응형