简体   繁体   English

将客户端javascript中的数组或哈希传递给服务器端ruby的好方法是什么?

[英]What are good ways of passing an array or hash in client side javascript to server side ruby?

主要标准是易于操作和便携。

JSON would be my choice, easy to generate in javascript and just as easy to parse directly into a hash in Ruby. JSON将是我的选择,易于在javascript中生成,并且很容易直接解析为Ruby中的哈希。

Ruby (irb session): Ruby(irb会话):

>> require 'json'
=> true
>> {:name => 'Chris Cherry', :emails => ['test1@test.com', 'test2@test.com']}.to_json
=> "{"emails":["test1@test.com","test2@test.com"],"name":"Chris Cherry"}"
>> json_string = _
=> "{"emails":["test1@test.com","test2@test.com"],"name":"Chris Cherry"}"
>> JSON.parse(json_string)
=> {"name"=>"Chris Cherry", "emails"=>["test1@test.com", "test2@test.com"]}

Since you are using rails, you can take advantage of the fact that ActiveSupport has JSON support. 由于您使用的是rails,因此可以利用ActiveSupport支持JSON的优势。

ruby-1.9.2-p136 :003 > j = ActiveSupport::JSON
 => ActiveSupport::JSON 
ruby-1.9.2-p136 :004 > j.encode({:team => "Celtics", :players => "20"})
 => "{\"team\":\"Celtics\",\"players\":\"20\"}" 
ruby-1.9.2-p136 :005 > j.decode("{\"team\":\"Celtics\",\"players\":\"20\"}")
 => {"team"=>"Celtics", "players"=>"20"}

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

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