我試圖從動作中獲得一些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數據。
想法?
當您嘗試使用的dataType關於什麼的?或者針對相同的URL發出請求,但將.json附加到它。問題在於jQuery將此分類爲失敗的請求,因爲響應格式與期望的格式不匹配。 – 2012-02-27 13:02:11
什麼是路線? – 2012-02-27 13:02:34
@TanelSuurhans我試過dataType,並且在url中有.json,成功不會被觸發。和瑞安https://github.com/railsware/js-routes只是一個JS腳本,可以幫助您與鐵路路線,方便得心應手。 – 2012-02-27 13:22:10