目前要完成靜態頁面生成的主要方法有簡單的模板替換、常見的ASP+FSO等,接下來介紹一種更爲簡單的方法,原理就是藉助XMLHTTP對象獲取目標頁面的源代碼,然後寫入到靜態網頁文件中。
Dim filename,fso,fout
filename="index.html"
Setfso=server.CreateObject("Scripting.FileSystemObject")
path=server.MapPath(filename)
Set fout=fso.CreateTextFile(path)
fout.WriteLine("<!--This page iscreated by program on "&now&" automatically-->")
webstr = getHTTPPage("http://url")
fout.WriteLine(webstr)
fout.close
set fout=nothing
set fso=nothing
'生成後讓網頁自動關閉
Response.Write("<script>")
Response.Write("functionToClose(){")
Response.Write("window.opener=null;window.close();}")
Response.Write("setTimeout(ToClose,10000);")
Response.Write("</script>")
'獲取目標網頁的源代碼
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")
if len(Http.responseBody)<1000 then
Response.End()
end if
set http=nothing
if err.number<>0 then err.Clear
End Function
'字符轉換,解決中文亂碼問題
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
另外可以設置這段程序定時執行,先把代碼寫到一個ASP文件裏,然後在另一網頁中使用JS調用定時程序,當然還有另外一種方法,就是用windows的任務計劃,這裏的方法是把下面代碼寫入一靜態頁中,然後在瀏覽器打開網頁
<script>
function run(){
window.open('make_html.asp','_blank');}
setInterval(run,5000);
</script>
在JavaScript中使用XMLHttpRequest對象獲取網頁代碼的方法,在返回中文的時候會出現亂碼的原因是:
1、xtmlhttp 返回的數據默認的字符編碼是utf-8,如果客戶端頁面是gb2312或者其它編碼就會產生亂碼
2、post方法提交的數據默認字符編碼也是utf-8,如果服務器端是gb2312或其他編碼數據就會產生亂碼
解決方法:
1、若客戶端是gb2312編碼,則在服務器指定輸出流編碼
Response.ContentType ="text/html"
Response.Charset = "GB2312"
2、服務器端和客戶端都使用utf-8編碼
還有一個常見的編碼問題是URL編碼解碼問題,下面使用JavaScript實現asp中的UrlEncode和UrlDecode功能,這裏也可以學到JavaScript如何調用VBscript的函數
<scriptlanguage="vbscript">
Function str2asc(strstr)
str2asc = hex(asc(strstr))
End Function
Function asc2str(ascasc)
asc2str = chr(ascasc)
End Function
</script>
本文爲Anyforweb技術分享博客,需要了解網站建設相關,請訪問anyforweb.com。