2013-05-20 41 views
0

我正在學習使用haml的padrino,並在使用遠程表單時遇到這種奇怪的行爲。用於創建元素的部分像魅力一樣工作,但更新後使用的部分以明文形式呈現。我敢肯定它是一個菜鳥的錯誤,但我似乎無法找到它。Padrino遠程js形式呈現爲文本而不是js

#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 

回答

1

對不起,讓喜歡這些無人看管的問題了這麼久。

您遇到的問題是update.js.haml指示Haml將其呈現爲純文本,而不是在腳本標記內。這就是爲什麼瀏覽器永遠不會運行它;你應該使用:javascript代替,如下:

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

以任何方式,你將要引用外部資產,即真正的JS文件最次。如果您需要在加載時使用一些數據引導這些數據,您可以查看替代方法,例如注入包含變量的腳本標記,該變量將設置初始數據並在應用程序中使用它(有不同的方法)。或者,您可以通過AJAX或WS加載數據,請記住,這會創建更多連接到服務器,並可能讓用戶等待,因此,如果數據需要在負載情況下準備好,比如說,您不是一個好方法正在建造SPA。