简体   繁体   中英

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.

Ruby (irb session):

>> 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.

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"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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