2011-04-05 91 views
2

我有一个控制器:简单的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> 

当我点击 '你好' 链接我看到你好()方法被调用,但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="https://stackoverflow.com/questions/hello" data-remote="true">hello</a> 
<br/> 

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



</body> 
</html> 
+0

您正在使用哪个版本的导轨? – Ashish 2011-04-05 10:16:40

+0

http://stackoverflow.com/questions/5511787/rails-2-to-rails-3-using-link-to-instead-of-link-to-remote-including-remote-an – Ciryon 2011-04-05 10:18:55

+0

@Ashish:Rails3 – demas 2011-04-05 10:20:52

回答

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 %>. 
+0

1.我需要把hello.js.erb放在哪里? view \ questions \ hello.js.erb? 2.我需要安装jQuery吗? – demas 2011-04-05 10:30:40

+0

是的......你需要jQuery。你需要在/ views/questions文件夹中保存hello.js.erb – Ashish 2011-04-05 10:34:45

+0

我不能使它工作。如果你看看我的代码(https://github.com/demas/test_ruby_ajax)并告诉我有关我的错误的信息,我会很感激。 – demas 2011-04-05 10:54:24

3

问题这里不必返回从控制器的任何行动,因为你正在使用AJAX,你需要返回的结果要么.js文件或杰森

看看这个例子中,Rails3中和jQuery

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

欢呼

sameera

+0

感谢这个例子的链接:-)非常有助于清除rails中的ajax的概念:-) +1! – 2013-03-21 21:59:30