ruby on rails 4 中利用 remote:true 实现 ajax ,小记

2 篇文章 0 订阅

_form.html.erb

<%= form_for @post, :remote => true do |f| %>
  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br />
    <%= f.number_field :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

postcontroller.rb

  def new
    @post = Post.new
    respond_to do |format|
      format.html
      format.json { render json:@product }
      format.js
    end
  end

index.html.erb

<h1>Listing products</h1>

<table>
  <tr>
    <th>Name</th>
    <th>Price</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>
  <tbody id="products">
<% @products.each do |product| %>
<%= render "product", :product => product %>
<% end %>
</tbody>
</table>

<br />

<%= link_to 'New Product', new_product_path, :remote => true, :id => "new_product_link" %>


new.js.erb

$('#new_post_link').hide().after('<%= j render("form") %>');

------------------------------------------------------------------------------------------------------

  def create
    @product = Product.new(params[:product])

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
        format.json { render json: @product, status: :created, location: @product }
        format.js
      else
        format.html { render action: "new" }
        format.json { render json: @product.errors, status: :unprocessable_entity }
        format.js
      end
    end
  end
create.js.erb

<% if @product.errors.count == 0 %>

	$('#new_product').remove();
	$('#new_product_link').show();
	$('#products').append('<%= j render("product", :product => @product) %>');

<% else %>

	$('.new_product').remove();
	$('#new_product_link').after('<%= j render("form") %>');

<% end %>

_product.html.erb

<tr id="product_<%= product.id %>">
  <td><%= product.name %></td>
  <td><%= product.price %></td>
  <td><%= link_to 'Show', product %></td>
  <td><%= link_to 'Edit', edit_product_path(product), :remote => true %></td>
  <td><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' }, :remote => true %></td>
</tr>




------------------------------------------------------------------------------------------------------

链接这里讲的详细

打开demo

打开源代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值