简体   繁体   English

在通过Ajax调用将JavaScript哈希发送到Rails操作方面需要帮助

[英]Need help in sending javascript hash to rails action through ajax call

This is my JS function, 这是我的JS函数,

function checkHash() { 函数checkHash(){

var myHash = {"apples": 3, "oranges": 4, "bananas": 42}

var url = '../../some_contoller/some_action'
var pars = 'myHash=' + encodeURIComponent(myHash)


var myAjax = new Ajax.Request(
  url,
    {
      method: 'get',
      asynchronous: asyncFlag,
      parameters: pars,
      onSuccess: function(transport) {

        //alert(transport.responseText);
        try {
          tax_hash = eval('('+transport.responseText+')');
          //alert("tax_hash = " + tax_hash)
        }
        catch(err){
          return

        }    
     onFailure: function() {
     }

} } }}
)
} }

Rails action, Rails动作,

def some_action def some_action

p params    ##It will print {"myHash"=>"[object Object]"}

end 结束

I want to print {"apples": 3, "oranges": 4, "bananas": 42} 我想打印{“ apples”:3,“ oranges”:4,4,“ bananas”:42}

First off, it's not a good idea to use eval on the results of your AJAX request. 首先,对您的AJAX请求结果使用eval不是一个好主意。 It's much better to have the request be interpreted as JSON (if that's all you're using it for). 最好将请求解释为JSON(如果这就是您要使用的全部内容)。

Here is info on how to tell rails to return JSON: http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-json 这是有关如何告诉Rails返回JSON的信息: http : //guides.rubyonrails.org/layouts_and_rendering.html#rendering-json

Also I would recommend only returning the params you're interested in and not all of them: 我也建议只返回您感兴趣的参数,而不是全部返回:

def some_action
    render json: params.reject {|k,v| ![:action,:controller, :other_params].include?(k)}
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM