隨筆-167  評論-65  文章-0  trackbacks-0

          由于最近老是在表單提交后出現沒有反應的現象,發現是在action中的使用render redirect_to的原因,于是就想搞清楚他兩真正的區別在哪里,上一遍的blog也談到了這二者的區別,但是有點淺,

          http://www.aygfsteel.com/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 閱讀(1504) 評論(1)  編輯  收藏 所屬分類: Rails

          評論:
          # re: 深刻理解render 和 redirect_to 2013-01-07 09:12 | zyp731
          簡單,明了,好帖。  回復  更多評論
            
          已訪問數:
          free counters
          主站蜘蛛池模板: 河北省| 木兰县| 青阳县| 无为县| 西乌珠穆沁旗| 绍兴市| 波密县| 康乐县| 吉首市| 池州市| 临潭县| 临海市| 邛崃市| 呈贡县| 元江| 门源| 双流县| 四平市| 呼玛县| 华安县| 紫云| 城步| 蒙阴县| 得荣县| 宣恩县| 苍梧县| 青冈县| 图木舒克市| 北宁市| 濮阳市| 托克托县| 增城市| 丁青县| 闸北区| 西充县| 静海县| 辽阳县| 左权县| 香河县| 扶沟县| 连城县|