嗨,大家好我是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
正確值應該是'/ welcome/show'。你說它沒有返回任何結果,但我想這可能是另一個需要解決的問題 – 2014-09-06 14:44:59
也是'id'作爲參數,如果你打算這樣做,我認爲你需要修復你的路由來'welcome/show''而不是'welcome/show /:id'' – 2014-09-06 14:45:52