2014-09-06 63 views
-1

嗨,大家好我是Rails的新手,我無法通過使用ajax傳遞路由。我已經閱讀了一些關於此問題的其他SO帖子,但我認爲我沒有正確理解它們。我怎樣才能得到ajax使用路徑格式Rails會識別如下:localhost:3000/welcome/show/hi-me?或者我應該改變我的rails代碼來匹配ajax?Rails使用ajax路由傳遞參數

Ajax調用(在index.html.erb)

//if url = 
// /welcome/show result: no ajax result 
// welcome/show result: GET http://localhost:3000/welcome/welcome/show?id=hi-me 404 (Not Found) 
// /show   result: GET http://localhost:3000/show?id=hi-me 404 (Not Found) 
// show   result: no ajax result 

$.ajax({ 
    url: '/show', 
    type: 'GET', 
    data: {id: 'hi-me'}, 
    success: function(data) {console.log('success: '+data);}, 
    error: function(data) {console.log('error: '+data);} 
}); 

的routes.rb

Rails.application.routes.draw do 
get 'welcome/show/:id' => 'welcome#show' 
get 'welcome/index' 
get 'welcome/show' 

welcome_controller

class WelcomeController < ApplicationController 
    def index 
    #render plain: "value: |#{params[:id]}|" 
    #redirect_to :controller=>'welcome', :action => 'show', :message => params[:id] 
    end 

    def show 
    render plain: "value: #{params[:id]}" 
    end 
end 
+0

正確值應該是'/ welcome/show'。你說它沒有返回任何結果,但我想這可能是另一個需要解決的問題 – 2014-09-06 14:44:59

+0

也是'id'作爲參數,如果你打算這樣做,我認爲你需要修復你的路由來'welcome/show''而不是'welcome/show /:id'' – 2014-09-06 14:45:52

回答

1

如果你想使用/welcome/show/hi-me則:

  • 您的路線是正確的get 'welcome/show/:id' => 'welcome#show'
  • 但你的Ajax不是,你需要的URL與在PARAMS沒有id更改爲/welcome/show/hi-me

但是,如果你想使用/welcome/show?id=hi-me,則:

  • 您的路線應該是get 'welcome/show' => 'welcome#show'
  • 你的AJAX會url: '/welcome/show'params: {id: 'hi-me}

不知道是否爲Ajax調用重定向響應可以重定向發起頁面或沒有,但你可以返回一個JavaScript重定向

def index 
    respond_to do |format| 
    format.js 
    end 
end 

然後創建一個名爲模板index.js.erb

window.location = '<%= whatever_path %>' 
+0

我試過了你的兩個建議,但第一個在修改後沒有重定向(在控制檯中沒有錯誤),第二個(我更喜歡)顯示成功:值:在控制檯中,沒有別的。任何其他想法? – Rilcon42 2014-09-06 15:10:53

+0

好,所以第二種方法正在工作,但沒有任何被返回?檢查你在控制器中的動作,它返回什麼 – 2014-09-06 15:12:25

+0

derp,我犯了一個語法錯誤。它現在在控制檯中返回hi-me,但它不會重定向到您已經在顯示頁面上的顯示頁面 – Rilcon42 2014-09-06 15:19:17