在我的rails3应用程序中,用户可以通过单击“添加项目”链接将项目添加到列表中。单击此链接可使AJAX调用以获取new_item表单。那部分我有工作。问题是,当我提交new_item表单时,即使我已指定,它似乎也不会被识别为“远程”表单:remote =>真正。很明显,我需要在从服务器返回new_item表单并注入页面之后重新初始化UJS或其他东西,但我不知道怎么做?
这是我的代码:
_new.html.haml(新项目表单)
= form_for [@list, @item], :remote => true, :html => {:class => 'form-inline'} do |f|
.input-append
= f.text_field "name", :class => 'input-large', :placeholder => "Add item to this list"
%button#picture.btn
%span.icon-camera
%button#link.btn{:style => "font-size: 10px;"}
http://
#link-field.field.margin.hidden-field-margin
= f.text_field "link", :placeholder => "http://www.link.com", :style => "width: 325px"
#picture-field.field.margin.hidden-field-margin
= f.file_field "picture"
= f.hidden_field "picture_cache"
.clearfix
= f.submit "Add Item", :class => 'btn', :id => "add-item"
lists.js.coffee
# this retrieves the new item form and places it in-line in the page
$("#new_list")
.bind "ajax:success", (evt, xhr, settings) ->
$("#list-item").html(xhr)
# when the new item form (returned from the server) is submitted here, it doesn't appear to be submitted via AJAX
$("#new_item #add-item")
.live "ajax:success", (evt, xhr, settings) ->
alert "this request worked"
items_controller.rb
class ItemsController < ApplicationController
respond_to :html, :xml, :json
def create
@list = List.find(params[:list_id])
@item = @list.items.create!(params[:item])
if @item.save
respond_with do |f|
f.html do
if request.xhr?
f.json { render :json => {:result => "ok"}}
else
redirect_to @list, :notice => "Item was successfully created."
end
end
end
end
end
end
当我提交new_item表单时,我在JS控制台中看到这样的错误...我有一个create.js.erb模板,它只是空白,但它没有找到这个并且显然没有识别请求作为ajax请求。如果没有更好的单词,我如何将从服务器返回的表单再次启用为“ujs”?
Template is missing
Missing template items/create, application/create with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee, :haml]}. Searched in: * "/Users/aressidi/Projects/intralist/app/views" * "/Users/aressidi/.rvm/gems/ruby-1.9.3-p194/gems/devise-2.1.2/app/views"
编辑 - 这是更新后的控制器代码,可以触发警报。
class ItemsController < ApplicationController
respond_to :html, :xml, :json
def create
@list = List.find(params[:list_id])
@item = @list.items.create!(params[:item])
if @item.save
respond_with do |f|
f.html do
if request.xhr?
render :json => {:result => "ok"}
else
redirect_to @list
end
end
end
end
end
end
答案 0 :(得分:1)
普通:remote => true
发出接受application/javascript, */*
(或类似内容)的请求。但是你的控制器没有响应javascript,所以它试图渲染html模板。
尝试在表单中强制json
:
= form_for [@list, @item], :remote => true, :html => {:class => 'form-inline', 'data-type' => 'json'} do |f|