3
我有一個名爲post的腳手架,它有一個標題和一個描述。在我的佈局中,我有一個鏈接來創建一個新的帖子:remote => true。當我點擊該遠程鏈接來更改div的內容時,我將如何創建它,以便創建一個新帖子?Rails 3.1 Ajax問題
我有一個名爲post的腳手架,它有一個標題和一個描述。在我的佈局中,我有一個鏈接來創建一個新的帖子:remote => true。當我點擊該遠程鏈接來更改div的內容時,我將如何創建它,以便創建一個新帖子?Rails 3.1 Ajax問題
假設您將使用的操作稱爲new
。 您應該創建一個名爲new.js.erb
的文件到視圖/帖子中,當您遠程張貼表單時將會呈現該文件。該文件必須包含將新帖子放入要填寫的div的JavaScript。作爲一個例子,它可能包含
# new.js.erb
$('div#container').html("<p><%= escape_javascript(@post.title) %></p>").append("<p><%= escape_javascript(@post.content) %></p>");
在ajax發佈完成並且新帖子被創建後,javascript將被立即執行。請記住以下幾點: - 你必須包括jQuery的 - 你必須在posts_controller指定渲染.js文件格式的功能,像
# posts_controller.erb
def create
@post = Post.new(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to(@post, :notice => 'Post created via non AJAX.') }
format.js # the actual ajax call
else
format.html { render :action => "new" }
end
end
end
東西