【发布时间】:2014-09-06 14:42:43
【问题描述】:
大家好,我是 Rails 的新手,我在使用 ajax 传递路线时遇到了麻烦。我已经阅读了有关此问题的其他一些 SO 帖子,但我认为我没有正确理解它们。如何让 ajax 使用 Rails 可以识别的路由格式,例如:localhost:3000/welcome/show/hi-me?或者我应该更改我的 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。你说它没有返回结果,但我想这可能是另一个需要解决的问题 -
你也将
id作为参数传递,如果你打算这样做,我认为你需要将你的路线固定到'welcome/show'而不是'welcome/show/:id'
标签: jquery ruby-on-rails ajax ruby-on-rails-4