#include 指令用于在多重頁面上創建需重復使用的函數、頁眉、頁腳或者其他元素等。
ASP 文件引用
#include 指令
通過使用 #include 指令,我們可以在服務器執行 ASP 文件之前,把另一個ASP文件插入這個文件中。#include 命令用于在多個頁面上創建需要重復使用的函數、頁眉、頁腳或者其他元素等。
如何使用 #include 指令
這里有一個名為 "mypage.asp" 的文件:
<html> <body> <h2>Words of Wisdom:</h2> <p><!--#include file="wisdom.inc"-->
</p> <h2>The time is:</h2> <p><!--#include file="time.inc"-->
</p> </body> </html>
這是 "wisdom.inc" 文件:
"One should never increase, beyond what is necessary, the number of entities required to explain anything."
這是 "time.inc" 文件:
<% Response.Write(Time) %>
在瀏覽器中查看的源代碼應該類似這樣:
<html> <body> <h2>Words of Wisdom:</h2> <p>"One should never increase, beyond what is necessary, the number of entities required to explain anything."</p> <h2>The time is:</h2> <p>11:33:42 AM</p> </body> </html>
Including 文件的語法:
如需在 ASP 中引用文件,請把 #include 命令置于注釋標簽之中:
<!--#include virtual="somefilename"-->
或者:
<!--#include file ="somefilename"-->
關鍵詞 Virtual
關鍵詞 virtual 指示路徑以虛擬目錄開始。
如果 "header.inc" 文件位于虛擬目錄 /html 中,下面這行代碼會插入文件 "header.inc" 中的內容:
<!-- #include virtual
="/html/header.inc" -->
關鍵詞 File
關鍵詞 File 指示一個相對的路徑。相對路徑起始于含有引用文件的目錄。
假設文件位于 html 文件夾的子文件夾 headers 中,下面這段代碼可引用 "header.inc" 文件的內容:
<!-- #include file
="headersheader.inc" -->
注意:被引用文件的路徑是相對于引用文件的。假如包含 #include 聲明的文件不在 html 目錄中,這個聲明就不會起效。
您也可以使用關鍵詞 file 和語法 (..) 來引用上級目錄中的文件。
提示和注釋
在上面的一節中,我們使用 ".inc" 來作為被引用文件的后綴。注意:假如用戶嘗試直接瀏覽 INC 文件,這個文件中內容就會暴露。假如被引用的文件中的內容涉及機密,那么最好還是使用 "asp" 作為后綴。ASP 文件中的源代碼被編譯后是不可見的。被引用的文件也可引用其他文件,同時一個 ASP 文件可以對同一個文件引用多次。
重要事項:在腳本執行前,被引用的文件就會被處理和插入。
下面的代碼無法執行,這是由于 ASP 會在為變量賦值之前執行 #include 命令:
<% fname="header.inc" %> <!--#include file="<%=fname%>"-->
不能在腳本分隔符之間包含文件引用:
<% For i = 1 To n <!--#include file="count.inc"--> Next %>
但是這段腳本可以工作:
<% For i = 1 to n %> <!--#include file="count.inc" --> <% Next %>