ASP 引用文件


#include 指令

通过使用 #include 指令,您可以在服务器执行 ASP 文件之前,把另一个 ASP 文件的内容插入到这个 ASP 文件中。

#include 指令用于创建函数、页眉、页脚或者其他多个页面上需要重复使用的元素等。

如何使用 #include 指令

这里有一个名为 "mypage.asp" 的文件:

  1. <!DOCTYPE html>
    <html>
    <body>
    <h3>Words of Wisdom:</h3>
    <p><!--#include file="wisdom.inc"--></p>
    <h3>The time is:</h3>
    <p><!--#include file="time.inc"--></p>
    </body>
    </html>

这是 "wisdom.inc" 文件:

  1. "One should never increase, beyond what is necessary,
    the number of entities required to explain anything."

这是 "time.inc" 文件:

  1. <%
    Response.Write(Time)
    %>

如果您在浏览器中查看源代码,它将如下所示:

  1. <!DOCTYPE html>
    <html>
    <body>
    <h3>Words of Wisdom:</h3>
    <p>"One should never increase, beyond what is necessary,
    the number of entities required to explain anything."</p>
    <h3>The time is:</h3>
    <p>11:33:42 AM</p>
    </body>
    </html>

引用文件的语法

如需在 ASP 页面中引用文件,请把 #include 指令放在注释标签中:

  1. <!--#include virtual="somefilename"-->

    or

    <!--#include file ="somefilename"-->

Virtual 关键词

请使用关键词 virtual 来指示以虚拟目录开始的路径。

如果一个名为 "header.inc" 的文件位于虚拟目录 /html 中,下面这行代码会插入 "header.inc" 文件中的内容:

  1. <!-- #include virtual ="/html/header.inc" -->

File 关键词

请使用关键词 file 来指示一个相对路径。相对路径是以含有引用文件的目录开始的。

如果您在 html 目录中有一个文件,且 "header.inc" 文件位于 html 头部,下面这行代码将在您的文件中插入 "header.inc" 文件中的内容:

  1. <!-- #include file ="headersheader.inc" -->

请注意被引用文件 (headersheader.inc) 的路径是相对于引用文件的。如果包含 #include 声明的文件不在 html 目录中,这个声明就不会生效。

提示和注释

在上面的一部分中,我们已经使用 ".inc" 来作为被被引用文件的文件扩展名。请注意:如果用户尝试直接浏览 INC 文件,这个文件中内容将会被显示出来。如果您的被引用文件中的内容包含机密的信息或者是您不想让任何用户看到的信息,那么最好还是使用 ".asp" 作为扩展名。ASP 文件中的源代码被编译后是不可见的。被引用的文件也可引用其他文件,同时一个 ASP 文件可以对同一个文件引用多次。

重要事项:在脚本执行前,被引用的文件就会被处理和插入。下面的脚本无法执行,这是由于 ASP 会在为变量赋值之前执行 #include 指令:

  1. <%
    fname="header.inc"
    %>
    <!--#include file="<%fname%>"-->

您不能在脚本分隔符之间包含文件引用。下面的脚本无法执行:

  1. <%
    For i = 1 To n
    <!--#include file="count.inc"-->
    Next
    %>

但是这段脚本可以执行:

  1. <% For i = 1 to n %>
    <!--#include file="count.inc" -->
    <% Next %>