2012-02-27 33 views
2

我試圖從動作中獲得一些json,但我遇到了問題。製作ajax請求並在rails動作中返回成功

我知道你可以返回「format.js」並返回一個「.js.erb」文件,但是......想象一下,我有一個返回一些東西的動作,我想以兩種不同的方式處理它。我不能在同一個.js.erb上有這兩種不同的方式,因爲當我返回它時,兩種方式都會被執行,對吧?我的意思是,當我返回該文件時,該文件將被完全處理。

所以我試圖用jQuery的方式。

我:

# GET /posts/slug/hidden_content.json 
def hidden_content 
    @post = Post.find(params[:id]) 
    @post = hidden_post_part(@post.body) 

    respond_to do |format| 
    format.json { render json: @post, :status => :ok} 
    end 
end 

而在controller.coffee:

$ -> 
    # Render hidden part of post 
    $(".showallpost img").click(-> 
    post_url = $(this).next().attr("href").split("/").pop(); 
    $.ajax 
     url: Routes.hidden_content_path(post_url), 
     type: "GET", 
     contentType: "application/json", 
     success: (data) -> 
     console.log "foo" 
); 

的GET完美的作品,並返回我所需要的,但成功的功能是從來沒有所謂的,我不知道看到「foo」日誌。

我想操作應該返回的東西告訴調用者GET成功。 (我嘗試過:狀態沒有運氣)。

所以我不能使用我的GET數據。

想法?

+0

當您嘗試使用的dataType關於什麼的?或者針對相同的URL發出請求,但將.json附加到它。問題在於jQuery將此分類爲失敗的請求,因爲響應格式與期望的格式不匹配。 – 2012-02-27 13:02:11

+0

什麼是路線? – 2012-02-27 13:02:34

+0

@TanelSuurhans我試過dataType,並且在url中有.json,成功不會被觸發。和瑞安https://github.com/railsware/js-routes只是一個JS腳本,可以幫助您與鐵路路線,方便得心應手。 – 2012-02-27 13:22:10

回答

0

在你js.erb,你可以把一個

<% if success %> 
    some javascript you want to execute on success 
<% else %> 
    some stuff you want to do on failure 
<% end %> 
+0

問題是我想從不同視圖使用該操作並以其他方式使用數據。該解決方案不起作用,這就是爲什麼我想以舊的方式使用Ajax。 – 2012-02-27 14:27:13

0

我嘗試了非常相似的一段代碼,和它的作品 -

$ -> 
    # Render hidden part of post 
    $(".showallpost").click -> 
    #post_url = $(this).next().attr("href").split("/").pop(); 
    $.ajax 
     url: "/posts/1.json", #Routes.hidden_content_path(post_url), 
     type: "GET", 
     contentType: "application/json", 
     success: (data) -> 
     console.log "foo" 

我建議你檢查什麼網址是前請求被髮送。它可能會被Jquery的跨域請求檢查困擾,並且根本不會被解僱 - 當我使用「localhost:3000/posts/1.json」作爲url而不是「posts/1.json」時發生在我身上