随笔-167  评论-65  文章-0  trackbacks-0

由于最近老是在表单提交后出现没有反应的现象,发现是在action中的使用render redirect_to的原因,于是就想搞清楚他两真正的区别在哪里,上一遍的blog也谈到了这二者的区别,但是有点浅,

http://www.blogjava.net/fl1429/archive/2009/03/10/258886.html

下面从我们的程序实验开始:

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

在对应的views->test目录下有test1.rhtml,test2.rhtml,test3.rhtml,内容随便写,例如内容都为 hello word

3,启动webrick

到相应的目录下Ruby script/server

4,浏览器中浏览页面

(1)页面test1.rhtml: http://localhost:3000/test/test1

浏览器中直接输入地址结果是:

可能是:

1test1A 
2test1B
3 127.0.0.1 - - [12/Mar/2009:18:10:11 中国标准时间] "GET /test/test1 HTTP/1.1" 304 0 - -> /test/test1 
 

也可能是:

1127.0.0.1 - - [12/Mar/2009:18:29:50 中国标准时间] "GET /test/test1 HTTP/1.1" 304 0 - -> /test/test1 
2test1A
3test1B 

 

(2)页面: test2.rhtml http://localhost:3000/test/test2

结果:

1test2A 
2test2B 
3127.0.0.1 - - [12/Mar/2009:18:11:10 中国标准时间] "GET /test/test2 HTTP/1.1" 302 98 - -> /test/test2 127.0.0.1 - - [12/Mar/2009:18:11:10 中国标准时间] "GET /test/test1 HTTP/1.1" 304 0 - -> /test/test1
4test1A 
5test1B 

  还可以发现最后,浏览器的地址的变为: http://localhost:3000/test/test1

 

(3)页面test3.rhtml  http://localhost:3000/test/test3

1test3A 
2test3B 
3127.0.0.1 - - [12/Mar/2009:18:12:29 中国标准时间] "GET /test/test3 HTTP/1.1" 302 98 - -> /test/test3 
4test3A 
5test3B 
6127.0.0.1 - - [12/Mar/2009:18:12:29 中国标准时间] "GET /test/test3 HTTP/1.1" 302 98 - -> /test/test3

 

执行效果是死循环.

由上述实验得到结论:

1,无论是render 还是 redirect_to 都是方法体内的内容全部执行完再跳转,就算跳转了,方法体内的还是会全部执行的

2,render 是跳转到对应的viewrhtml

3,redirect_to 是跳转到对应的 action ,所以页面三执行的效果死循环!







write by feng
posted on 2009-03-12 18:48 fl1429 阅读(1491) 评论(1)  编辑  收藏 所属分类: Rails

评论:
# re: 深刻理解render 和 redirect_to 2013-01-07 09:12 | zyp731
简单,明了,好帖。  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 
已访问数:
free counters