开发者

how to dynamically populate javascript data structure

开发者 https://www.devze.com 2023-03-05 17:46 出处:网络
when an user click on my display link, it goes to my display page, a javascript runs after the page load and render the display.something like below:

when an user click on my display link, it goes to my display page, a javascript runs after the page load and render the display. something like below: ... display_data_hash = {}

function display() { // use display_data_hash here } ...

is it possible to populate "display_data_hash" in my javascript on the server side? or should i just add tag to my view and populate display_data_hash inside my html. i really don't want mix开发者_JS百科 javascript with html.


First approach using AJAX

you could retrieve your display_data_hash using AJAX (jQuery here) like:

$.getJSON('/yourcontroller/youraction.json', function(data) {

   display(data);

});

and in your controller you render a json response like:

class YourController < ApplicationController
   def your_display_action

      @my_data = .....

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

Second Approach without AJAX

If you don't want to fire an AJAX request you could do something like:

In your layout view add a section:

<html>
<head>
....
<script type="text/javascript">
    <%= yield :inline_js %>
</script>
....
</head>
<body>
....
</body>
</html>

then create a helper method like:

def insert_display_data(display_data) {

  # convert hash to json
  data_json = display_data.to_json

  content_for :inline_js do
     "display('#{data_json}');"
  end
}

and in your display JavaScript function do:

function display(data) {

  if(data instanceof String) { 
     // parse JSON using jquery
     data = $.parseJSON(data);
  }

  // your code...
}
0

精彩评论

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

关注公众号