开发者

Simple AJAX example

I have a controller:

class QuestionsController < ApplicationController
  def hello
    puts "===============开发者_Python百科=====!!!==================="
    @hello = "hey"
    "some"
  end

  def test
  end

test.rhtml:

<%= javascript_include_tag :defaults %>

<br/>
Click this link to show the current 
<br/>

<%= link_to "hello", 
    { :controller => "questions", :action => "hello" },
    :update => 'time_div', 
    :remote => true %>.

<br/>
<div id='time_div'>
  ...
</div>

When I click on 'hello' link I see that hello() method was called, but html page remains the same. Why?

How do I need to change code to update HTML page?

Here is generated HTML page:

<!DOCTYPE html>
<html>
<head>
  <title>Stack</title>


  <script src="/javascripts/jquery.js?1286229922" type="text/javascript"></script>
<script src="/javascripts/jquery-ujs.js?1286229922" type="text/javascript"></script>
  <meta name="csrf-param" content="authenticity_token"/>
<meta name="csrf-token" content="UKPX1dNCZhyTk8u71hR9KaUmufIire7Rhvg8t7cRSlM="/>

</head>

<body>



<br/>
Click this link to show the current 
<br/>

<a href="/questions/hello" data-remote="true">hello</a>
<br/>

<div id='time_div'>
  ...
</div>



</body>
</html>


You can have your hello action like this:

def hello
  #### your code goes here #####
  respond_to do |format|
    format.js { render :layout=>false }
  end
end

And one file hello.js.erb

$("#time_div").html("some text");

And your link will be:

<%= link_to "hello", { :controller => "questions", :action => "hello" }, :remote => true %>.


problem here is you are not returning anything from the controller action, Since you are using AJAX you need to return the result as either .js or jason

have a look at this example, with rails3 and Jquery

https://github.com/nu7hatch/rails3-ujs-example

cheers

sameera

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜