简单的AJAX示例

时间:2011-04-05 10:04:50

标签: ruby-on-rails ajax

我有一个控制器:

class QuestionsController < ApplicationController
  def hello
    puts "====================!!!==================="
    @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>

当我点击'hello'链接时,我看到调用了hello()方法,但html页面保持不变。为什么呢?

如何更改代码以更新HTML页面?

这是生成的HTML页面:

<!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>

2 个答案:

答案 0 :(得分:4)

你可以这样做你好的行动:

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

一个文件hello.js.erb

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

您的链接将是:

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

答案 1 :(得分:3)

这里的问题是你没有从控制器动作返回任何东西,因为你使用的是AJAX,你需要将结果返回为.js或jason

看一下这个例子,使用rails3和Jquery

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

欢呼声

sameera