简体   繁体   中英

ajax, link_to remote in ruby on rails

i am new to ruby on rails. i am following a tutorial to understand how ajax works on rails using link_to and remote=true. i have the following codes.

// in view/home/sample.html.erb

<head> <%= javascript_include_tag "prototype.js" %> </head>
<body>
<div id="time_div">
 <%= link_to("click here",  :update=>'time_div' ,:url=>{:action => :say_when} , :remote => true) %>
</div>
</body>

// in /controllers/home_controller.rb

def sample
end

def say_when
   render_text "<p>The time is <b>" + DateTime.now.to_s + "</b></p>"
end

i've put prototype.js in assets/javascripts folder. But i am not getting the time on browser. plz someone help

You're missing the javascript that will update the div content with the result of the Ajax request. You can try like this:

create say_when.js.erb with the following content

$("time_div").update('<%= escape_javascript("<p>The time is <b>#{DateTime.now.to_s}</b></p>")%>');

You can remove the method say_when from the controller, there is no code needed in it anymore, Rails will call directly the say_when.js.erb file.

Look at this #205 Unobtrusive Javascript Railscast that might explain things.

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