Rails路由传递带ajax的参数

时间:2014-09-06 14:42:43

标签: jquery ruby-on-rails ajax ruby-on-rails-4

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

1 个答案:

答案 0 :(得分:1)

如果您想使用/welcome/show/hi-me,那么:

  • 您的路线正确get 'welcome/show/:id' => 'welcome#show'
  • 但是您的ajax不是,您需要将网址更改为/welcome/show/hi-me而参数中没有id

但是如果你想使用/welcome/show?id=hi-me那么:

  • 您的路线应为get 'welcome/show' => 'welcome#show'
  • 您的ajax将是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 %>'