由于最近老是在表單提交后出現(xiàn)沒有反應(yīng)的現(xiàn)象,發(fā)現(xiàn)是在action中的使用render 和 redirect_to的原因,于是就想搞清楚他兩真正的區(qū)別在哪里,上一遍的blog也談到了這二者的區(qū)別,但是有點(diǎn)淺,
http://m.tkk7.com/fl1429/archive/2009/03/10/258886.html
下面從我們的程序?qū)嶒?yàn)開始:
1,建立controller
test_controller.rb
class TestController < ApplicationController

def test1
puts "test1A"
render :action => "test1"
puts "test1B"
end

def test2
puts "test2A"
redirect_to :action => "test1"
puts "test2B"
end

def test3
puts "test3A"
redirect_to :action => "test3"
puts "test3B"
end

end

2,建立view
在對應(yīng)的views->test目錄下有test1.rhtml,test2.rhtml,test3.rhtml,內(nèi)容隨便寫,例如內(nèi)容都為 hello word
3,啟動webrick
到相應(yīng)的目錄下Ruby script/server
4,瀏覽器中瀏覽頁面
(1)頁面test1.rhtml: http://localhost:3000/test/test1
瀏覽器中直接輸入地址結(jié)果是:
可能是:
1
test1A
2
test1B
3
127.0.0.1 - - [12/Mar/2009:18:10:11 中國標(biāo)準(zhǔn)時(shí)間] "GET /test/test1 HTTP/1.1" 304 0 - -> /test/test1
也可能是:
1
127.0.0.1 - - [12/Mar/2009:18:29:50 中國標(biāo)準(zhǔn)時(shí)間] "GET /test/test1 HTTP/1.1" 304 0 - -> /test/test1
2
test1A
3
test1B
(2)頁面: test2.rhtml http://localhost:3000/test/test2
結(jié)果:
1
test2A
2
test2B
3
127.0.0.1 - - [12/Mar/2009:18:11:10 中國標(biāo)準(zhǔn)時(shí)間] "GET /test/test2 HTTP/1.1" 302 98 - -> /test/test2 127.0.0.1 - - [12/Mar/2009:18:11:10 中國標(biāo)準(zhǔn)時(shí)間] "GET /test/test1 HTTP/1.1" 304 0 - -> /test/test1
4
test1A
5
test1B
還可以發(fā)現(xiàn)最后,瀏覽器的地址的變?yōu)?/span>: http://localhost:3000/test/test1
(3)頁面test3.rhtml http://localhost:3000/test/test3
1
test3A
2
test3B
3
127.0.0.1 - - [12/Mar/2009:18:12:29 中國標(biāo)準(zhǔn)時(shí)間] "GET /test/test3 HTTP/1.1" 302 98 - -> /test/test3
4
test3A
5
test3B
6
127.0.0.1 - - [12/Mar/2009:18:12:29 中國標(biāo)準(zhǔn)時(shí)間] "GET /test/test3 HTTP/1.1" 302 98 - -> /test/test3
執(zhí)行效果是死循環(huán).
由上述實(shí)驗(yàn)得到結(jié)論:
1,無論是render 還是 redirect_to 都是方法體內(nèi)的內(nèi)容全部執(zhí)行完再跳轉(zhuǎn),就算跳轉(zhuǎn)了,方法體內(nèi)的還是會全部執(zhí)行的
2,render 是跳轉(zhuǎn)到對應(yīng)的view下rhtml
3,redirect_to 是跳轉(zhuǎn)到對應(yīng)的 action 里,所以頁面三執(zhí)行的效果是死循環(huán)!
posted on 2009-03-12 18:48
fl1429 閱讀(1500)
評論(1) 編輯 收藏 所屬分類:
Rails