json更新后,Rails3用js响应

问题描述

| 使用http://blog.bernatfarrero.com/in-place-editing-with-javascript-jquery-and-rails-3/ gem使用json进行更新,但是如何触发update.js.erb更新页面的不同部分? 编辑 在发票页面中使用它。发票中的每个项目都有一个价格字段,可以使用best_in_place进行更新。 仅在成功更新字段后,才需要更新订单项的总价格和发票的应付金额。 最终得到类似:
 respond_to do |format|
        if @item.update_attributes(params[:item])
          format.html { redirect_to order_url(@item.order_id),:notice => \"Successfully updated item.\" }
          format.js {  }
          format.json { head :ok } 
编辑了best_in_place.js行#175
loadSuccessCallback : function(data) {
    this.element.html(data[this.objectName]);
        // Binding back after being clicked
    $(this.activator).bind(\'click\',{editor: this},this.clickHandler);
    if(this.objectName == \"item\") $.getScript(\'update.js\'); // If its an item,call update.js.erb 
  },
    

解决方法

您不需要视图update.js.erb。正如ezkl已经指出的那样,您需要将控制器的response_to设置为json。另外,您需要在public / javascripts / application.js中激活就地最佳
$(document).ready(function() {
  jQuery(\".best_in_place\").best_in_place()
});
并添加到您的视图中:
 <td><%= best_in_place task,:name,:type => :input,:nil => \"Click to edit\" %></td>
我在自己的网站上有一个关于Prototype和JQuery的Ajax教程-JQuery部分使用了就地最佳方法:http://www.communityguides.eu/articles/15     ,我想对best_in_place pcasa做完全相同的事情。在当前版本(1.0.2)中,loadSuccessCallback函数触发ajax:success事件。这使您可以在application.js中执行此操作:
$(\'.best_in_place\')
    .best_in_place()
    .bind(\'ajax:success\',function(e) {
        // do your post-json call magic
    });
    ,您是否尝试过以下方法:
def update
  @user = User.find(params[:id])

  respond_to do |format|
    if @user.update_attributes(params[:user])
      format.html { redirect_to(@user,:notice => \'User was successfully updated.\') }
      format.json { head :ok }
      format.js
    else
      format.html { render :action => \"edit\" }
      format.json  { render :json => @user.errors,:status => :unprocessable_entity }
    end
  end
end
我尚未使用本教程中的代码对其进行测试,但其想法是必须告诉控制器方法来加载Javascript文件。我不确定这将如何与重定向交互,但是原理是正确的。