我最近问了这个问题:Javascript 表单提交?
现在我试图弄清楚为什么在提交表单后,create.js.erb没有加载最新的数据(提交的数据)。
如果我再次提交数据,表格将更新倒数第二个数据,但不是绝对最新的。
...为什么?
编辑:
最新代码 -
类别控制器:类 Admin::CategoriesController < Admin::AdminController ...
def create
@category = Admin::Category.new(params[:admin_category])
# You can't retrieve the @categories before attempting to add new one. Keep at end of create method.
@categories = Admin::Category.all
respond_to do |format|
if @category.save
save_to_history("The category \"#{@category.name}\" has been created", current_user.id)
format.json { render json: { html: render_to_string(partial: 'categories') } }
# I've tried both the above and bellow
#format.json { render json: { html: render_to_string('categories') } }
format.html { redirect_to(admin_categories_url, :notice => 'Category was successfully created.') }
format.xml { render :xml => @category, :status => :created, :location => @category }
else
format.html { render :action => "new" }
format.xml { render :xml => @category.errors, :status => :unprocessable_entity }
end
end
end
...
end
Javascript:
<script type='text/javascript'>
$(function(){
$('#new_admin_category').on('ajax:success', function(event, data, status, xhr){
$("#dashboard_categories").html(data.html);
});
});
</script>
解决了
我使用@PinnyM 的方法并添加了一个带有以下代码的 create.json.erb 文件:
<% self.formats = ["html"] %>
{
"html":"<%= raw escape_javascript( render :partial => 'categories', :content_type => 'text/html') %>"
}
并将我的创建方法更改为:
def create
@category = Admin::Category.new(params[:admin_category])
respond_to do |format|
if @category.save
# You can't retrieve the @categories before attempting to add new one. Keep after save.
@categories = Admin::Category.all
save_to_history("The category \"#{@category.name}\" has been created", current_user.id)
format.json
format.html { redirect_to(admin_categories_url, :notice => 'Category was successfully created.') }
format.xml { render :xml => @category, :status => :created, :location => @category }
else
format.html { render :action => "new" }
format.xml { render :xml => @category.errors, :status => :unprocessable_entity }
end
end
end
如果这很混乱,请提供建议。