大家好,我是Rails的新手,我在使用ajax传递路线方面遇到了麻烦。我已经阅读了关于这个问题的其他一些SO帖子,但我认为我没有正确理解它们。如何让ajax使用路由格式Rails会识别出:localhost:3000 / welcome / show / hi-me?或者我应该更改我的rails代码以匹配ajax?
ajax call(在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 :(得分:1)
如果您想使用/welcome/show/hi-me
,那么:
get 'welcome/show/:id' => 'welcome#show'
/welcome/show/hi-me
而参数中没有id
但是如果你想使用/welcome/show?id=hi-me
那么:
get 'welcome/show' => 'welcome#show'
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 %>'