简体   繁体   中英

how to monitor instance variable from ruby controller pass to view html using AJAX

Hi I want to create a page where it monitors(view) or render the value of the variable inside the controller dynamically as the iteration of variable goes by.

view.html.erb

<a id='get_value' class="btn">Run</a>
<ul id="value_variable_from_controller"><ul>

<script>
var getTheValue=function(){
      $.ajax({
        type:'GET',
        url:'/run/results',
        success:function(data,status){
        <!--how to dynamically UPDATE the value_variable_from_controller?-->
        alert("Successfully");
        }
      });
    }
    $(document).on("click","#get_value",getTheValue);
</script>

And here's my controller where i iterate the value of x,

results.rb

x=0
5.times do 
 x++
 sleep(1)
 #HOW TO RETURN THE VALUE OF VAR X EVERY UPDATE?
 #render :json => x, :status => :ok #do i need to have a loop in js?
end

Many Thanks.

If I understand you correctly you want to update the value in the HTML document every time it is updated on the server, correct? There are ways to accomplish this, although the transitioning of state between client and server is usually initiated by the client . 1

To combat this, websockets are currently the most popular approach - basically opening up a two-way communication pipe between the client and the server. Of course, for your simple example this might be overkill (unless you require heavy real-time interactions between the client and the server - then it's certainly worth taking a gander at) - and something like polling might be more suitable (which is indeed initiated by the client), although it will generate a large number of requests.

You might also consider long polling which only opens one connection.

Polling is a technique in which the client calls the server requesting data at a certain interval, which would work for your situation. From the code you posted it also seems like you want it to be possible to fetch the value by clicking on the #get_value link, which can utilise the same method as the long polling service. Here's an example:

// in your view/javascript
$(document).ready(function() {
  function getValue(trigger) { 
    $.ajax({
      type: 'GET',
      url: '/run/results/',
      success: function(data, status) {
        $('#value_variable_from_controller').text(data.x);
        if(trigger) { 
          setTimeout(getValue(true), 1000); }
      }
    )} // end AJAX
  } // end getValue

  // binding the action to your link as well
  $('#get_value').on('click', function(event) {
    event.preventDefault();
    getValue(false);
  });
  // start the polling
  getValue(true);
}); 

# in your controller
 @x = 0 # initial value
def results
  @x++ # increment every time this action is called
  render @x.to_json
end

This way the client initialises the data flow, and the server mutates state in response to a client request - which is the norm in a client/server architecture.

1 The client–server characteristic describes the relationship of cooperating programs in an application. The server component provides a function or service to one or many clients, which initiate requests for such services. ( http://en.wikipedia.org/wiki/Client%E2%80%93server_model )

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