【问题标题】:how pass variable from controller to application.js?如何将变量从控制器传递到 application.js?
【发布时间】:2015-07-28 12:44:01
【问题描述】:

请帮忙解决问题。

我为在数据库中创建新记录做了 ajax-from:

<%= form_for [current_user, @album], :html => { 'data-current-user' => current_user.id }  do |f| %>
  <%= f.text_field :title %>
  <%= f.submit %>
<% end %>
<table id="albumsList">
  <thead>
    <tr>
      <th colspan="3"></th>
    </tr>
  </thead>
  <tbody data-current-user="<%= current_user.id %>">
    <% @albums.each do |album| %>
      <tr>
        <td><%= album.title %></td>
        <td><%= link_to 'Show', user_album_path(current_user, album.id) %></td>
        <td><%= link_to 'Edit', edit_user_album_path(current_user, album) %></td>
        <td><%= link_to 'Destroy', user_album_path(current_user, album), method: :delete, data: { confirm: 'Are you sure?' } %>---<span class="destroy_album" data-album-id="<%= album.id %>">destroy</span></td>
      </tr>
    <% end %>
  </tbody>
</table>

application.js:

$('#new_album').on('submit', function(e){
  e.preventDefault();

  var currentUserId = $(this).attr('data-current-user'),
      albumTitle = $('input#album_title').val();

  $.ajax({
    url: '/users/' + currentUserId + '/albums',
    type: 'POST',
    data: $('#new_album').serialize(),
    success: function(result){
      handleModal('album create', 'is successfull', '00ff2a', 2000);
      $('#albumsList tbody').append('<tr> \
        <td>' + albumTitle + '</td> \
        <td></td> \
        <td></td> \
        <td><span class="destroy_album" data-album-id="??????">destroy</span></td> \
      </tr>');
    }
  })
});  

function handleModal(title, body, colorHex, timeout){
  // bla bla bla
}

相册控制器:

  def create
    @album = current_user.albums.build(album_params)

    if @album.save
      # @album_id = @album.id
      redirect_to new_user_album_path(@current_user)
    else
      redirect_to new_user_album_path(@current_user), :status => 403 
    end
  end

结果用户提交表单并:

  1. 通过ajax-request 在数据库中创建一个新记录。
  2. 在表格中添加了带有专辑名称的新行

但我需要元素 .destroy_album 添加属性 data-album-id 和 @album.id 值。为此,我需要将 @album.id 从控制器传递到 application.js 和 tpl.html.erb

【问题讨论】:

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


    【解决方案1】:

    将此添加到type: 'POST'上方的ajax请求中

     dataType: "JSON", 
    

    当你做出 json 响应时,试试这个

    def create
      @album = current_user.albums.build(album_params)
    
      if @album.save
        render json: @album, status: ok
      else
        render json: @album, status: 403
      end
    end
    

    现在成功了

    你可以像这样检索id

    result.id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-08
      • 2021-09-20
      相关资源
      最近更新 更多