简体   繁体   中英

How would I bring in Jquery items to update an index.erb in Sinatra?

So I have a simple game, in the index.erb, the code is as follows:

<div class="battleInfo">
  <h2> Your HP: <%= @my_knight.hp %> </h2>
  <h2> Dragon HP: <%= @my_dragon.hp %> </h2>

  <h1> <%= @results %> </h1>
</div>

I want to use Jquery in the public folder as app.js, to update the HP info so we can see the whole run down of the characters and how they die.

The JS code:

function postHP() {
      $(".battleInfo").append(my_knight.hp);
      $(".battleInfo").append(my_dragon.hp);
};

I get an error that my_knight is not defined. If I use @my_knight , it says the @ is an illegal character.

It's my first week of Ruby and I'm not sure how to get this to work and can't find the answer online.

I guess the basic question would be how to get info from js into sinatra. I have the CSS working just fine.

Any help is appreciated, thanks

Firstly, you need to understand what is happening where/when. Firstly, client is making a request. Rails receives a request, instantiate controller, which sets instance variables. Then rails gets your erb file, finds all <%.. %> blocks and substitute/execute commands in there. This results in pure HTML which is being send back to the customer.

When customer receives html, it loads all the css and javascript files referenced in this html. This javascript has absolutely no access to controller's instance variables - it has no idea they have ever existed, it has no idea it is rails application, doesn't know what controller is etc.

The most common way to pull any sort of data back to the view is to send an AJAX - this means that the browser will make an additional call to your server, which will return a JSON object, understandable by javascript and which can be used to update the loaded HTML.

There are number of steps to implement this. First of all, you need to create a new action in your controller, like update_hp or sth. Then you have to trigger AJAX call with your javascript and define a handler (functions) to handle successful response from the server. This handler will most likely update the requested fields.

You can see some examples on how to build AJAX request here , and some details on building json responses here . The topic is too broad to describe it here. Give it a go and come back when you're stuck.

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