将变量从jquery传递到Rails控制器

问题描述:

我需要将通过jquery从客户端捕获的变量传递给控制器​​,以便可以在服务器端使用它.经过一番谷歌搜索之后,我发现我们可以通过Ajax调用来传递它.

I need to pass a variable which is captured from client side via jquery to controller, so that it can be used in the server side. After googling a bit, I found that we can pass it via an Ajax call.

routes.rb

get "mymethod?Id=", :to => "sample#mymethod"

j1.js

$(function(){

var test = 1;

$(.btn).click(function(){

  $.ajax({
           url: '/mymethod?Id='+ test,
           success: function(data) {
                 }
         });
    });

});

sample_controller.rb

def mymethod
 session[:Id] = params["Id"];
end

当我尝试使用session [:Id]时,它总是为零.

When I try to use session[:Id], it is always nil.

任何想法,

谢谢

如果您想在jquery中发出GET请求,最好这样做:

If you want to make a GET request in jquery you'd be better off doing:

$.ajax({
    url: '/mymethod',
    success: function(data){ // anything },
    data: { Id: test }
});

因为它为您urlencode并正确设置了参数格式.

Because it urlencode and format the parameters correctly for you.

在rails中,删除对routes.rb中Id的引用,只需在控制器中使用params词典即可访问变量Id(信息在此处:

In rails, remove the reference to the Id in routes.rb and just use the params dictionary in your controller to access the variable Id (info here: http://rails.nuvvo.com/lesson/6371-action-controller-parameters)