嗨,大家好我是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