0

当我调用 $.getJSON 时,我想重新加载 tbody 元素。换句话说,我需要删除所有元素并通过 Json 响应放置新元素。

JS

$(document).ready(function(){
  $('#position').sortable({
    update: function(event, ui) {
        var newOrder = $(this).sortable('toArray').toString();
         $.getJSON('/save_positions.json', {ids:newOrder}, function(data){
            ??????
         });
    }
  });
});

我的观点

# index.html.erb

<tbody id="position">
  <%= render :partial => "activities"%>
</tbody>

局部视图

#_activities.html.erb

<% @activities.each do |activity| %>
  <tr id='<%= activity.id %>'>
    <td><%= activity.position %></td>
    <td><%= link_to activity.id, activity_path(activity) %></td>
    <td><%= activity.name %></td>
    <td><%= activity.estimated %></td>
    <td><%= activity.used %></td>
    <td><%=l activity.created_at %></td>
  </tr>

我的动作(应用程序控制器)

def save_positions
  @activities = Activity.all(:order => 'position')

  respond_to do |format|
    format.json { render :json => @activities }
  end
end
4

1 回答 1

1

从您的代码中,我得到的印象是您正在尝试做的是在服务器端生成新的 HTML 并将其插入到文档中。如果是这种情况,请尝试以下操作:

$.get( '/save_positions', { ids : newOrder } ).done( function( data ) {

  $( "#position" ).html( $( data ).html() );

} );

如果您真的想返回 JSON,那么您可能希望返回一个对象数组并对其进行迭代以生成新的 HTML,可能使用像 Mustache 这样的模板引擎,例如:

没有模板引擎:

$.getJSON( '/save_positions.json', { ids : newOrder } ).done( function( data ) {

  var positions = [];

  $.each( data, function ( key, val ) {

    // generate an element
    var el = $( "<tr>" );

    // ...

    positions.push( el );

  } );

  $( "#position" ).empty().append( positions );

} );

或者

JS:

$.getJSON( '/save_positions.json', { ids : newOrder } ).done( function( data ) {

  var positions = Mustache.render( template, data );

  $( "#position" ).html( positions );

} );

胡子模板:

{{#positions}}

<tr id='{{activity.id}}'>
  <td>{{activity.position}}</td>
  <td>{{activity.url}}</td>
  <td>{{activity.name}}</td>
  <td>{{activity.estimated}}</td>
  <td>{{activity.used}}</td>
  <td>{{activity.created_at}}</td>
</tr>

{{/positions}}
于 2012-08-04T14:45:28.737 回答