0

我正在学习将 padrino 与 haml 一起使用,并且在使用远程表单时遇到了这种奇怪的行为。用于创建元素的部分就像一个魅力,但更新后使用的部分以明文形式呈现。我确定这是一个菜鸟错误,但我似乎找不到它。

#user.rb
get :show, :with => :id do
    @user = User.get(params[:id].to_i) #REWRITE
    @posts = @user.posts
    session[:user_id] = @user.id
    render 'user/show'
end

#post.rb
  put :update, :with => :id, :provides => :js do
    @post = post.first(:id => params[:post][:id].to_i, :user_id => session[:user_id].to_i)
    @post.attributes(:name => params[:post][:name], :up => params[:post][:up], 
                      :down => params[:post][:down])
    if @post.save
      render 'post/update'
    end
  end

#show.haml
#show
  .user
    .title= link_to @user.login, url_for(:user, :show, :id => @user.id)
    .date= time_ago_in_words(@user.created || Time.now) + ' ago'
    .password= @user.password
  #posts= partial 'post/list', :locals => { :posts => @user.posts }

#_post.haml
.post{:id => "post#{post.id}"}
  .name= post.name
  .date= time_ago_in_words(post.created || Time.now) + ' ago'
  - if post.up
    .up + 
  - if post.down 
    .down -
  = link_to "(x)", url(:post, :destroy, :id => post.id, :format => :js, :method => 'delete'), :confirm => "Sure?", :remote => true
  = link_to "(e)", url(:post, :edit, :id => post.id, :format => :js), :remote => true

#_edit.haml
- form_for :post, url(:post, :update, :id => @post.id, :format => :js), :remote => true, :method => 'put', :id => 'post_edit_form' do |f|
  = partial 'post/form', :locals => {:f => f}
  = f.text_field :id, :hidden => true
  = f.submit "Edit", :class => 'button'

#update.js.haml
:plain
  alert("ok");

单击编辑按钮后,我得到一个白页: alert("ok"); 为什么 update.js.haml 页面没有呈现为远程 js?

WEBrick 日志:

DEBUG -  TEMPLATE (0.0003s) /habit/update.js
DEBUG -       PUT (0.0170s) /habit/update/1.js - 200 OK
4

1 回答 1

1

很抱歉让这些问题无人看管这么久。

您遇到的问题update.js.haml是指示 Haml 将其呈现为纯文本,而不是在脚本标签内。这就是浏览器永远不会运行它的原因。您应该:javascript改为使用,如下所示:

#update.js.haml
:javascript
  alert("ok");

无论如何,大多数时候您都希望引用外部资产,即真正的 JS 文件。如果您需要在加载时使用一些数据引导那些,您可以查看替代方法,例如注入包含变量的脚本标记,该变量将设置初始数据并在您的应用程序中使用它(有不同的方法可以做到这一点)。或者,您可以通过 AJAX 或 WS 加载该数据,请记住,这会创建更多与服务器的连接并可能让用户等待,因此如果数据需要在加载时准备好,这不是一个好方法,例如,您'正在建立一个 SPA。

于 2014-04-10T09:20:23.213 回答