【问题标题】:Rails 4: passing custom data and form data in ajax callRails 4:在 ajax 调用中传递自定义数据和表单数据
【发布时间】:2016-03-05 20:46:59
【问题描述】:

我正在尝试以这种方式使用 ajax 调用提交一个简单的表单

$('#save-artificial-form').click(function () {
  var fd = $('#categories-form').serialize();
  console.log(fd);
  var url = "/categories";
  $.ajax({
    type: 'POST',
    url: url,
    data: $('#categories-form').serialize(),
    success: function() {
      return true;
    }
  });

它工作得很好并且可以保存表单数据。但是我想再添加一个数据category_type,但我不知道该怎么做。我想要这样的东西

data: $('#categories-form').serialize(), category_type: "advanced"

我该怎么做?在上面的fd variable中添加/推送category_type就可以了。

我的表单中的代码

<%= form_for(@category, :html => {:id => "categories-form", class: "form-alt"}) do |f| %>
  <% if @category.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@category.errors.count, "error") %> prohibited this category from being saved:</h2>
      <ul>
      <% @category.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :enabled %><br>
    <%= f.check_box :enabled %>
  </div>
    <div style="margin: 6px 0px 0 0 !important;">
      <%= link_to "This is test", 'javascript:void(0)', id: "save-artificial-form", :rel => "tooltip", :title => "save" %>
    </div>
<% end %>

【问题讨论】:

    标签: ruby-on-rails ajax ruby-on-rails-4 serialization


    【解决方案1】:

    选项 1:

    使用隐藏字段,它会自动添加到序列化字符串中

    <%= f.hidden_field :category_type, value: 'advanced' %>
    

    选项 2:

    将缺失值连接到序列化字符串,即。 "param=value"+ "&missing_data=bar"

    data: $('#categories-form').serialize() + '&category_type=advanced'
    

    【讨论】:

    • 隐藏字段对我有用,但我希望是否有办法通过添加变量 fd 或我想要的其他方式。
    猜你喜欢
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 2012-06-27
    • 2014-11-29
    • 2014-06-19
    • 2020-07-06
    相关资源
    最近更新 更多