最近做网站需要用到动态include asp文件,由于宏会预先编译,这就决定了 if...else...之间用下<!--#include file="....."--> 是不可行的,
度娘了下,发现网上关于这方面的代码还是有不少的,不过基本都是一个版本。。。相关代码如下:
Function include(filename)
Dim re,content,fso,f,aspStart,aspEnd
set fso=CreateObject("Scripting.FileSystemObject")
set f=fso.OpenTextFile(server.mappath(filename))
content=f.ReadAll
f.close
set f=nothing
set fso=nothing
set re=new RegExp
re.pattern="^\s*="
aspEnd=1
aspStart=inStr(aspEnd,content,"<%")+2
do while aspStart>aspEnd+1
Response.write Mid(content,aspEnd,aspStart-aspEnd-2)
aspEnd=inStr(aspStart,content,"%\>")+2
Execute(re.replace(Mid(content,aspStart,aspEnd-aspStart-2),"Response.Write "))
aspStart=inStr(aspEnd,content,"<%")+2
loop
Response.write Mid(content,aspEnd)
set re=nothing
End Function
重点来了,因为自己做的站点使用的是UTF-8编码的,所以用这段代码在include的时候就出问题了,中文乱码了。。。



function include(filename,str_charset)
set f_stream=server.CreateObject("ADODB.Stream")
f_stream.mode=3
f_stream.type=2
f_stream.open
f_stream.position=0
f_stream.charset=str_charset
f_stream.LoadFromFile server.MapPath(filename)
content = f_stream.ReadText
f_stream.close
set re=new RegExp
re.pattern="^\s*="
code_End=1
code_Start=instr(1,content,"<%")+2
do while code_Start > code_End + 1
'输出并执行ASP代码部分
code_End = instr(code_Start,content,"%\>") + 2
execute(re.replace(mid(content,code_Start,code_End - code_Start - 2),"response.Write "))
code_Start=instr(code_End,content,"<%")+2
loop
'输出非ASP代码部分
response.Write mid(content,code_End)
set re = nothing
end function
用法:<% include("需要包含的文件名","文件编码") %>
如此,基本所有现有任何编码都能正确显示了。。。 希望能给遇到相同问题的朋友带来帮助!
By --FlyDream