开发者

Help with JSON in rails

My back end is my Rails server which sends JSON data to my front end. In the front end, I am using javascript and jQuery which processes my JSON data and displays some of it.

Now, the user can inputs 开发者_高级运维a number depending on the data displayed to it.

So, on the basis of input from user, certain changes are made to JSON data received earlier and send it back to my back-end as properly encoded JSON.

My question is how can I process this JSON data at the server and store the inputs filled by the user?


Not sure why you'd need to send the data back as JSON since Rails can just handle the form data normally, as thomasfedb says. But if you definitely do need to, you can use the jQuery serializeArray method and then do a quick conversion from array to JSON. See the following:

http://api.jquery.com/serializeArray/#comment-47479466

If you go down this route, you could use the stringify method in JSON2.js to create valid JSON data from your object.

http://www.json.org/js.html


edited:

Sorry, just realised that you've already got that far! Should have read the question properly.

You can use this JSON ruby implementation to parse the JSON data:

JSON.parse(json_data, {:symbolize_names => true})

and then just use the save method from ActiveRecord::Base to save your record.


Let's assume you've used JQuery.post() to send the data to the server with a dataType of 'JSON'

Then in your controller you can do this:

MyController << ApplicationController

  def my_action
    @data = params[:data] // client data available as a Ruby Hash object

    // Process data into @result (for example)

    respond_to do |format|
      format.json { render :json => @result.to_json }
    end
  end

end

Or you could leave out the render statement above and provide a view (called my_action.json.erb) in which you can format the JSON response.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜