2011-04-05 98 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