⬆️ ⬇️

using JSON in Ruby on Rails, plus a var_dump example in Javascript

In this article, I will tell you% username%, how to work with JSON, as well as how to dump any javascript variable for debug.



First, a little theory. And so, based on the definition taken from Wikipedia .

JSON is a text-based data exchange format based on JavaScript and commonly used with this language. Like many other text formats, JSON is easy to read by people.



Since I personally am an idolater of the Ruby language and in particular the Ruby on Rails framework, I will describe the example of the server part on it. Although the principle is the same in all languages, I think fans of other languages ​​will understand it without problems.



On the server side we write something like:

 def MyController < ApplicationController def give_me_json data = Model.find(params[:id]) # ,      text/plain response.headers['Content-type'] = "text/plain; charset=utf-8" render :text => data.to_json end end 


We execute JavaScript on the client (note, do not forget to include the prototype library):

 new Ajax.Request('/MyController/give_me_json', { asynchronous:true, evalScripts:true, onComplete:function(request) { var x = eval('(' + request.responseText + ')'); alert(var_dump(x)); }, }) 


Or you can do it on Ruby on Rails like this:

 <%= remote_function(:complete => "var x = eval('(' + request.responseText + ')'); alert(var_dump(x));", :url => { :action => 'give_me_json', :id => link.id }) %> 


For var_dump, it's better to use not alert, of course, but create, for example: <div id='debug_element'></div> , and output by $('debug_element').innerHtml = var_dump(object);

')

Functions for dumping variable information on JavaScript are a great many. I prefer to use the function that I looked at here . Maybe not the most elegant option, but it suits me. Here is its code:

 function var_dump(arr,level) { var dumped_text = ""; if(!level) level = 0; //The padding given at the beginning of the line. var level_padding = ""; for(var j=0;j<level+1;j++) level_padding += " "; if(typeof(arr) == 'object') { //Array/Hashes/Objects for(var item in arr) { var value = arr[item]; if(typeof(value) == 'object') { //If it is an array, dumped_text += level_padding + "'" + item + "' ...\n"; dumped_text += var_dump(value,level+1); } else { dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n"; } } } else { //Stings/Chars/Numbers etc. dumped_text = "===>"+arr+"<===("+typeof(arr)+")"; } return dumped_text; } 


That's all. Lastly, IMHO, the string generated by JSON is more compact and sleeker than making a controller to generate a dynamic JavaScripta, like here . Or, God forbid, give away through Ajax.Updater a ready page with already placed HTML tags.

Source: https://habr.com/ru/post/51768/



All Articles