簡體   English   中英

使用ajax更新Rails視圖中的帖子

[英]using ajax to update posts in rails view

在Ajax中單擊“提交帖子”按鈕時,如何編寫用於添加帖子的javascript?該javascript文件是否稱為index.js.haml或create.js.haml? 以下是相關文件:

index.html.haml:

.post#new_post    
    - @posts.each do |post|
        = post.body
    = render partial: "form"

_form.html.haml:

= bootstrap_form_for @post, remote: true do |f|
    = f.text_area :body, label: "", required: true
    = f.submit "Submit Post", class: "button"

帖子控制器(索引和創建方法):

def index
    load_posts # a method I use for loading posts
end

def create
if @post.save
  respond_to do |format|
    format.js
    format.html do
      flash[:success] = "Saved."
    end
  end
else
  load_posts
  flash.now[:error] = "Sth went wrong. "
  render :index
end

結束

JS的ajaxifying:

$('#new_post').append('#{escape_javascript(render(@post))}');

非常感謝!

在您的視圖/帖子中創建一個文件create.js.haml並添加以下內容

$('#new_post').append("<%= @post.body %>");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM