網頁產生靜態Html檔案有許多好處,比如產生html網頁有利於被搜尋引擎收錄,不僅被收錄的快還收錄的全.前台脫離了資料訪問,減輕對資料庫訪問的壓力,加快網頁開啟速度.
像www.aspid.cn的主站就採用了TSYS產生html檔案!
所以吟清最近對產生html比較感興趣,看了不少文章,也有一點點收穫.
1,下面這個例子直接利用FSO把html代碼寫入到檔案中然後產生.html格式的檔案 <%
filename="test.htm"
if request("body")<>"" then
set fso = Server.CreateObject("Scripting.FileSystemObject")
set htmlwrite = fso.CreateTextFile(server.mappath(""&filename&""))
htmlwrite.write "<html><head><title>" & request.form("title") & "</title></head>"
htmlwrite.write "<body>輸出Title內容: " & request.form("title") & "<br /> 輸出Body內容:" & request.form("body")& "</body></html>"
htmlwrite.close
set fout=nothing
set fso=nothing
end if
%>
<form name="form" method="post" action="">
<input name="title" value="Title" size=26>
<br>
<textarea name="body">Body</textarea>
<br>
<br>
<input type="submit" name="Submit" value="產生html">
</form>
2,但是按照上面的方法產生html檔案非常不方便,第二種方法就是利用模板技術,將模板中特殊代碼的值替換為從表單或是資料庫欄位中接受過來的值,完成模板功能;將最終替換過的所有模板代碼產生HTML檔案.這種技術採用得比較多,大部分的CMS都是使用這類方法.
template.htm ' //模板檔案 <html>
<head>
<title>$title$ by aspid.cn</title>
</head>
<body>
$body$
</body>
</html> ?
TestTemplate.asp '// 產生Html <%
Dim fso,htmlwrite
Dim strTitle,strContent,strOut
'// 建立檔案系統對象
Set fso=Server.CreateObject("Scripting.FileSystemObject")
'// 開啟網頁模板檔案,讀模數板內容
Set htmlwrite=fso.OpenTextFile(Server.MapPath("Template.htm"))
strOut=f.ReadAll
htmlwrite.close
strTitle="產生的網頁標題"
strContent="產生的網頁內容"
'// 用真實內容替換模板中的標記
strOut=Replace(strOut,"$title$",strTitle)
strOut=Replace(strOut,"$body$",strContent)
'// 建立要產生的靜態頁
Set htmlwrite=fso.CreateTextFile(Server.MapPath("test.htm"),true)
'// 寫入網頁內容
htmlwrite.WriteLine strOut
htmlwrite.close
Response.Write "產生靜態頁成功!"
'// 釋放檔案系統對象
set htmlwrite=Nothing
set fso=Nothing
%>
3,第三種方法就是用XMLHTTP擷取動態網頁產生的HTML內容,再用ADODB.Stream或者Scripting.FileSystemObject儲存成html檔案。這句話是在藍色理想上看到的,對XMLHTTP吟清還不熟悉正在找資料瞭解.找到一段XMLHTTP產生Html的代碼參考一下.
<%
'常用函數
'1、輸入url目標網頁地址,傳回值getHTTPPage是目標網頁的html代碼
function getHTTPPage(url)
dim Http
set Http=server.createobject("MSXML2.XMLHTTP")
Http.open "GET",url,false
Http.send()
if Http.readystate<>4 then
exit function
end if
getHTTPPage=bytesToBSTR(Http.responseBody,"GB2312")
set http=nothing
if err.number<>0 then err.Clear
end function
'2、轉換亂瑪,直接用xmlhttp調用有中文字元的網頁得到的將是亂瑪,可以通過adodb.stream組件進行轉換
Function BytesToBstr(body,Cset)
dim objstream
set objstream = Server.CreateObject("adodb.stream")
objstream.Type = 1
objstream.Mode =3
objstream.Open
objstream.Write body
objstream.Position = 0
objstream.Type = 2
objstream.Charset = Cset
BytesToBstr = objstream.ReadText
objstream.Close
set objstream = nothing
End Function
txtURL=server.MapPath("../index.asp")
sText = getHTTPPage(txtURL)
Set FileObject=Server.CreateObject("Scripting.FileSystemObject")
filename="../index.htm"
Set openFile=FileObject.OpenTextfile(server.mapPath(filename),2,true) 'true為不存在自行建立
openFile.writeline(sText)
Set OpenFile=nothing
%>
<script>
alert("靜態網頁產生完畢");
history.back();
</script>