问题描述
大家好,我是Rails的新手,我无法使用Ajax传递路线.我已经阅读了有关此问题的其他一些SO帖子,但我认为我没有正确理解它们.我如何获得ajax以使用Rails会识别的路由格式,例如:localhost:3000/welcome/show/hi-me?还是应该更改Rails代码以匹配Ajax?
Hi guys I'm very new to Rails and I am having trouble passing a route using ajax. I have read a few other SO posts about this issue, but I don't think I understand them correctly. How can I get ajax to use a route format Rails will recognize like: localhost:3000/welcome/show/hi-me? Or should I be changing my rails code to match the ajax?
ajax调用(在index.html.erb中)
ajax call (in 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
routes.rb
Rails.application.routes.draw do
get 'welcome/show/:id' => 'welcome#show'
get 'welcome/index'
get 'welcome/show'
welcome_controller
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/hi-me
,则:
- 您的路线正确
get 'welcome/show/:id' => 'welcome#show'
- 但是您的ajax不是,您需要将参数中的URL更改为
/welcome/show/hi-me
且没有id
- Your route is correct
get 'welcome/show/:id' => 'welcome#show'
- But your ajax isn't, you'll need to change the url to
/welcome/show/hi-me
with noid
in the params
但是,如果您想使用/welcome/show?id=hi-me
,则:
But if you want to use /welcome/show?id=hi-me
then:
- 您的路线应为
get 'welcome/show' => 'welcome#show'
- 您的ajax将是
url: '/welcome/show'
和params: {id: 'hi-me}
- Your route should be
get 'welcome/show' => 'welcome#show'
- Your ajax would be
url: '/welcome/show'
andparams: {id: 'hi-me}
不确定ajax调用的重定向响应是否可以重定向初始页面,但是您可以返回javascript重定向
Not sure if a redirect response for ajax calls could redirect the initiating page or not, but you could return a javascript redirect
def index
respond_to do |format|
format.js
end
end
然后创建一个名为index.js.erb
window.location = '<%= whatever_path %>'
这篇关于带有ajax的Rails Routing pass参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!