#include 指令用于在多重頁(yè)面上創(chuàng)建需重復(fù)使用的函數(shù)、頁(yè)眉、頁(yè)腳或者其他元素等。
ASP 文件引用
#include 指令
通過(guò)使用 #include 指令,我們可以在服務(wù)器執(zhí)行 ASP 文件之前,把另一個(gè)ASP文件插入這個(gè)文件中。#include 命令用于在多個(gè)頁(yè)面上創(chuàng)建需要重復(fù)使用的函數(shù)、頁(yè)眉、頁(yè)腳或者其他元素等。
如何使用 #include 指令
這里有一個(gè)名為 "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) %>
在瀏覽器中查看的源代碼應(yīng)該類似這樣:
<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 文件的語(yǔ)法:
如需在 ASP 中引用文件,請(qǐng)把 #include 命令置于注釋標(biāo)簽之中:
<!--#include virtual="somefilename"-->
或者:
<!--#include file ="somefilename"-->
關(guān)鍵詞 Virtual
關(guān)鍵詞 virtual 指示路徑以虛擬目錄開(kāi)始。
如果 "header.inc" 文件位于虛擬目錄 /html 中,下面這行代碼會(huì)插入文件 "header.inc" 中的內(nèi)容:
<!-- #include virtual
="/html/header.inc" -->
關(guān)鍵詞 File
關(guān)鍵詞 File 指示一個(gè)相對(duì)的路徑。相對(duì)路徑起始于含有引用文件的目錄。
假設(shè)文件位于 html 文件夾的子文件夾 headers 中,下面這段代碼可引用 "header.inc" 文件的內(nèi)容:
<!-- #include file
="headersheader.inc" -->
注意:被引用文件的路徑是相對(duì)于引用文件的。假如包含 #include 聲明的文件不在 html 目錄中,這個(gè)聲明就不會(huì)起效。
您也可以使用關(guān)鍵詞 file 和語(yǔ)法 (..) 來(lái)引用上級(jí)目錄中的文件。
提示和注釋
在上面的一節(jié)中,我們使用 ".inc" 來(lái)作為被引用文件的后綴。注意:假如用戶嘗試直接瀏覽 INC 文件,這個(gè)文件中內(nèi)容就會(huì)暴露。假如被引用的文件中的內(nèi)容涉及機(jī)密,那么最好還是使用 "asp" 作為后綴。ASP 文件中的源代碼被編譯后是不可見(jiàn)的。被引用的文件也可引用其他文件,同時(shí)一個(gè) ASP 文件可以對(duì)同一個(gè)文件引用多次。
重要事項(xiàng):在腳本執(zhí)行前,被引用的文件就會(huì)被處理和插入。
下面的代碼無(wú)法執(zhí)行,這是由于 ASP 會(huì)在為變量賦值之前執(zhí)行 #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 %>