Beginning Rails 书的第 8 章有一个 Ajax 表单示例,它工作正常,但它不会输出无效输入的警报。
Controller 代码是:
def create
@comment = @article.comments.new(params[:comment])
if @comment.save
respond_to do |format|
format.html { redirect_to @article, :notice => 'Thanks for your comment' }
format.js
end
else
respond_to do |format|
format.html { redirect_to @article, :alert => 'Unable to add comment due to errors in your input'}
# logger.info("#{Time.now} Ajax invalid validation
##{@comment.errors.full_messages}!")
format.js { render 'fail.js.erb' }
end
end
end
'fail_create.js.erb' 文件包含一行;
alert("<%= @comment.errors.full_messages.to_sentence %>");
哪位好心人能解释一下为什么不行,谢谢
最佳答案
您正在呈现“fail.js.erb”,但在您的问题中您说文件“fail_create.js.erb”包含代码。这是您问题中的拼写错误还是您的代码中的问题?
此外,在 Rails 中使用 RJS 被认为是错误的形式。如果您正在阅读示例作为学习经验,那么您会更有力量,但它在 Rails 社区中是一个失败的实验。 Javascript 应该独立存在(最好不引人注意地添加到站点中)。
关于ajax - 警报在 Rails/ajax 情况下不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5925431/