加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在rails 3中以ajax方式提交表单(使用jQuery)

发布时间:2020-12-16 03:23:44 所属栏目:百科 来源:网络整理
导读:我是rails和jQuery的初学者。我在一个页面中有两个单独的表单,我想以ajax方式(使用jQuery)单独提交它们。这是我有多远。任何人都可以添加或修复此代码,使其工作。我使用Rails 3.1和jQuery 1.6。先谢谢你。 application.js $(".savebutton").click(function
我是rails和jQuery的初学者。我在一个页面中有两个单独的表单,我想以ajax方式(使用jQuery)单独提交它们。这是我有多远。任何人都可以添加或修复此代码,使其工作。我使用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,:class=>"round" %><br/>
  </fieldset>
  <p><%= button_to "save and continue",{:class=>"savebutton"} %></p>
<%end%>

学校控制器

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的形状相同

你想要:

>停止提交的正常行为。
>通过ajax发送到服务器。
>获得回复并相应地更改事情。

下面的代码应该这样做:

$('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
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读