首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >以Ajax方式(使用jQuery)在Rails 3中提交表单

以Ajax方式(使用jQuery)在Rails 3中提交表单
EN

Stack Overflow用户
提问于 2018-03-02 01:54:09
回答 2查看 0关注 0票数 0

我是Rails和jQuery的初学者。我在一个页面中有两个独立的表单,我想以Ajax方式(使用jQuery)分别提交它们。有人能添加或修复此代码以使其正常工作吗?我使用的是Rails 3.1和jQuery 1.6。

application.js

代码语言:txt
复制
$(".savebutton").click(function() { 
    $('form').submit(function() {
         $(this).serialize();
    });
}); 

表格一:

代码语言:txt
复制
<%=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%>

第二种形式:

代码语言:txt
复制
<%=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%>

控制器

代码语言:txt
复制
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
EN

回答 2

Stack Overflow用户

发布于 2018-03-02 10:33:37

你想:

  1. 停止提交的正常行为。
  2. 通过Ajax将其发送到服务器。
  3. 得到返回,并相应地改变事情。

下面的代码应这样做:

代码语言:txt
复制
$('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
});
票数 0
EN

Stack Overflow用户

发布于 2018-03-02 10:55:48

在你的表单上如果你用:remote => true,可以使用JavaScript将它们提交给

代码语言:txt
复制
$('form#myForm').trigger('submit.rails');
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100003556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档