怎樣動態include文件
ASP程序員經常面臨的最大挑戰之一是動態Include文件。由于#include 在ASP代碼執行之前處理,所以,看起來,動if/else的腦筋是不可能的。
真是這樣嗎?
根據你使用Include的目的,以及你將Include的文件數目,使用if/else也許可以解決問題。但這絕對不是任何時候可以奏效的,而且也不是一種有效的解決辦法,因為你需要做許多的手工工作。
假設有兩個樣本HTM文件,1.htm和2.htm,為簡化起見,假設文件的內容如下:
$#@60;!-- 1.HTM: --$#@62;
$#@60;font color=#ff0000$#@62;This is 1.htm$#@60;/font$#@62;
$#@60;!-- 2.HTM: --$#@62;
$#@60;font color=#0000ff$#@62;This is 2.htm$#@60;/font$#@62;
現在我們來試試動態Include:
$#@60;%
if request.querystring(‘param‘)=‘2’ then
%$#@62;
$#@60;!--#include file=‘2.htm’--$#@62;
$#@60;%
else
%$#@62;
$#@60;!--#include file=‘1.htm’--$#@62;
$#@60;%
end if
%$#@62;
請注意:上面的兩個#include 實際上都得到了處理。你可以實際運行一下,看看效果:
http://localhost/Test.asp?param=1
http://localhost/Test.asp?param=2
http://localhost/Test.asp
上面我們是把一個querystring作為條件。你還可以把時間、日期、瀏覽器版本等作為條件。但是,條件越復雜,這種方法的效率越差。下面提供了另外一種思路:
$#@60;%
if request(‘param‘)=‘2’ then
filespec = ‘2.htm’
else
filespec = ‘1.htm’
end if
filespec = server.mapPath(filespec)
scr = ‘scripting.fileSystemObject’
set fs = server.createobject(scr)
set f = fs.openTextFile(filespec)
content = f.readall
set f = nothing
set fs = nothing
response.write(content)
%$#@62;
在IIS5.0/ASP3.0中,有兩種新的方法來支持“動態包含”:
$#@60;%
server.transfer filename
server.execute filename
%$#@62;
如果正好使用的是IIS5.0和ASP3.0,那么Ok! 但是IIS5.0需要運行在Windows 2000上。
真是這樣嗎?
根據你使用Include的目的,以及你將Include的文件數目,使用if/else也許可以解決問題。但這絕對不是任何時候可以奏效的,而且也不是一種有效的解決辦法,因為你需要做許多的手工工作。
假設有兩個樣本HTM文件,1.htm和2.htm,為簡化起見,假設文件的內容如下:
$#@60;!-- 1.HTM: --$#@62;
$#@60;font color=#ff0000$#@62;This is 1.htm$#@60;/font$#@62;
$#@60;!-- 2.HTM: --$#@62;
$#@60;font color=#0000ff$#@62;This is 2.htm$#@60;/font$#@62;
現在我們來試試動態Include:
$#@60;%
if request.querystring(‘param‘)=‘2’ then
%$#@62;
$#@60;!--#include file=‘2.htm’--$#@62;
$#@60;%
else
%$#@62;
$#@60;!--#include file=‘1.htm’--$#@62;
$#@60;%
end if
%$#@62;
請注意:上面的兩個#include 實際上都得到了處理。你可以實際運行一下,看看效果:
http://localhost/Test.asp?param=1
http://localhost/Test.asp?param=2
http://localhost/Test.asp
上面我們是把一個querystring作為條件。你還可以把時間、日期、瀏覽器版本等作為條件。但是,條件越復雜,這種方法的效率越差。下面提供了另外一種思路:
$#@60;%
if request(‘param‘)=‘2’ then
filespec = ‘2.htm’
else
filespec = ‘1.htm’
end if
filespec = server.mapPath(filespec)
scr = ‘scripting.fileSystemObject’
set fs = server.createobject(scr)
set f = fs.openTextFile(filespec)
content = f.readall
set f = nothing
set fs = nothing
response.write(content)
%$#@62;
在IIS5.0/ASP3.0中,有兩種新的方法來支持“動態包含”:
$#@60;%
server.transfer filename
server.execute filename
%$#@62;
如果正好使用的是IIS5.0和ASP3.0,那么Ok! 但是IIS5.0需要運行在Windows 2000上。