【问题标题】:Couldn't submit the form无法提交表单
【发布时间】:2013-01-25 11:07:44
【问题描述】:

我想根据某些参数创建一个新对象。

在我的 new.html.haml 中

%table
   %thead
      %tr
        %td
          = f.label: type
         %td
           = select_tag :question_type, options_for_select
    %tbody#content

javascript:

$('#question_type').change(function(){
     $.ajax({
        data: { question_type: $(this).val() },
        url: window.location.href,
        dataType: 'script'
     });
  });

在我的 new.js.haml 中

$('#content').html("#{escape_javascript(render(:partial => "question_form"))}");

在_question_form.html.haml

= form_for @question, :url => {:action => "create"} do |f|
  %tr
    %td{:style => 'text-align:right;'}
      = f.label :name
    %td
      = f.text_field :name
  %tr
    %td
    %td
      = f.button :Submit, :value => 'Create'

在我的控制器中

def new
   @question = Question.new

   respond_to do |format|
     format.html
     format.js
   end
  end

  def create
   @question.save

   respond_to do |format|
     format.html (redirect_to questions_path)
     format.js
   end
  end

一切正常,但输入问题名称后我无法提交表单。如何让这个表单提交?

【问题讨论】:

  • “不能”是什么意思?不能点击按钮?或提交表单不会进入创建操作?还是别的什么?
  • 请帮助我。过去 2 天我一直在为此苦苦挣扎。
  • @jvnill 是的,我可以点击按钮,但我无法提交表单。当表单提交时,我可以调用 create 方法,但我不能可以提交表单。
  • 单击提交按钮时,Firebug 控制台会显示什么?

标签: javascript ruby-on-rails ajax ruby-on-rails-3 model-view-controller


【解决方案1】:

问题在于您的 html 结构。你应该把表格放在桌子外面。

= form_for @question do |f|
  %table

请注意,这将提交您可以在创建操作中忽略的问题类型

更新:

# new.html.haml
#form-content= render 'question_form'

# _question_form.html.haml
= form_for @question, :url => {:action => "create"} do |f|
  %table
    %thead
      %tr
        %td= f.label: type
        %td= select_tag :question_type, options_for_select
    %tbody
      - if params[:question_type].present?
        %tr
          %td{:style => 'text-align:right;'}= f.label :name
          %td= f.text_field :name
        %tr
          %td
          %td= f.button :Submit, :value => 'Create'

# new.js.haml
$('#form-content').html("#{escape_javascript render("question_form")}");

【讨论】:

  • 你的答案是正确的。我也试过了,但我无法将表单实例传递给我的 _question_form.html.haml,此页面有许多基于 question_type 的输入。至少帮我将表单实例传递给 _question.html.haml
  • 试试我更新的答案。您要做的是将表单放入部分中。
猜你喜欢
  • 2018-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-24
  • 1970-01-01
相关资源
最近更新 更多