asp专题提供asp的最新资讯内容,帮你更好的了解asp。
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"><%FilePath = Server.MapPath("/")&"/index.htm" 'response.Write(FilePath) Do_Url = "http://" Do_Url = Do_Url&Request.ServerVariables("SERVER_NAME")&"/default.aspx" strUrl = Do_Url 'response.Write(strUrl) dim objXmlHttp set objXmlHttp = Server.CreateObject("Microsoft.XMLHTTP") objXmlHttp.open "GET",strUrl,false objXmlHttp.send() Dim binFileData binFileData = objXmlHttp.responseBody Dim objAdoStream set objAdoStream = Server.CreateObject("ADODB.Stream") objAdoStream.Type = 1 objAdoStream.Open() objAdoStream.Write(binFileData) objAdoStream.SaveToFile FilePath,2 objAdoStream.Close()  Response.Write("<script language=javascript>alert('首页静态转换成功!');</script>")%>
分页:<%IF (cint(rs.PageCount))>1 THEN IF cint(cur) = 1 then  Response.write ("<a href="&curfile&"?keyword="&keyword&"&serType="&serType&"&cur=" & (cur+1) & "> [下一页] </a>")  Response.write ("<a href="&curfile&"?keyword="&keyword&"&serType="&serType&"&cur=" & cint(rs.PageCount) & "> [末 页] </a>") ELSEIF cint(cur) = cint(rs.PageCount) THEN  Response.write ("<a href="&curfile&"?keyword="&keyword&"&serType="&serType&"&cur=1> [首 页] </a>")  Response.write ("<a href="&curfile&"?keyword="&keyword&"&serType="&serType&"&cur=" & (cur-1) & "> [上一页] </a>") ELSE  Response.write ("<a href="&curfile&"?keyword="&keyword&"&serType="&serType&"&cur=1> [首 页] </a>")  Response.write ("<a href="&curfile&"?keyword="&keyword&"&serType="&serType&"&cur=" & (cur-1) & "> [上一页] </a>")  Response.write ("<a href="&curfile&"?keyword="&keyword&"&serType="&serType&"&cur=" & (cur+1) & "> [下一页] </a>")  Response.write ("<a href="&curfile&"?keyword="&keyword&"&serType="&serType&"&cur=" & cint(rs.PageCount) & "> [末 页] </a>") END IFEND IF%>分页set:<% cur = Request("cur") IF cur = "" or cur < 1 THEN cur = 1 rs.PageSize = perPageSize IF cint(cur) > cint(rs.PageCount) THEN cur = cint(rs.PageCount) END IF rs.AbsolutePage = cint(cur)     datacount = 1 %>
<%'禁止网页缓存Response.Buffer = TrueResponse.ExpiresAbsolute = Now() - 1Response.Expires = 0Response.CacheControl = "no-cache"'验证码生成dim yz2randomize timeryz2=Int((8999)*Rnd +1009)session("ok")=yz2%>删除文件 iFileName 文件名 iPath 文件路径<% '有关文件操作 'Power by huang_ke@hotmail.com  '删除文件 iFileName 文件名 iPath 文件路径 sub DelFile(iFileName,iPath)   realpath = Server.MapPath(iPath) & "" & iFileName  Set fso = Server.CreateObject("Scripting.FileSystemObject")  fso.DeleteFile(realpath)    Set fso = nothing  end sub%>
在ASP编程中使用数组 数组的定义Dim MyArrayMyArray = Array(1,5,123,12,98)可扩展数组Dim MyArray()for i = 0 to 10ReDim Preserve MyArray(i)MyArray(i)=inext将一个字符串分割并返回分割结果的数组Dim MyArrayMyArray = Split(tempcnt,chr(13)&chr(10))For I = Lbound(MyArray) to Ubound(MyArray) Response.Write MyArray(I) & "<br>"Next 数组排序函数function..Sort(ary) KeepChecking = TRUE Do Until KeepChecking = FALSE KeepChecking = FALSE For I = 0 to UBound(ary) If I = UBound(ary) Then Exit For If ary(I) > ary(I+1) Then FirstValue = ary(I) SecondValue = ary(I+1) ary(I) = SecondValue ary(I+1) = FirstValue KeepChecking = TRUE End If Next Loop Sort = ary End function..数组排序函数应用例子Dim MyArray MyArray = Array(1,5,123,12,98)MyArray = Sort(MyArray) For I = Lbound(MyArray) to Ubound(MyArray) Response.Write MyArray(I) & "<br>"Next 在Application和Session中使用数组Application.LockApplication("StoredArray") = MyArrayApplication.UnlockLocalArray = Application("StoredArray")覆盖Application中的数组Application.LockApplication("StoredArray") = LocalArrayApplication.UnlockSession使用方法与Application相同从数据库中把数据导入数组中Dim MyArray取出全部记录MyArray = RS.GetRows取出前10项记录MyArray = RS.GetRows(10)For row = 0 To UBound(MyArray, 2)For col = 0 To UBound(MyArray, 1)Response.Write (col, row) & "<br>"NextNext
 Set fso = Server.CreateObject("Scripting.FileSystemObject")  Set fout = fso.Createtextfile(server.mappath("..eshopview"&rs("bname")),true) fout.writeline okfilefout.closeFiLePaTh = Server.MapPath("....commerceview")&""&tempfnameSet fso = CreateObject("Scripting.FileSystemObject")fso.DeleteFile(filepath)If img<>"" then FiLePaTh = Server.MapPath("uploadmember")&""&img : fso.DeleteFile(FilePath)Set fso = nothing
 一、先介绍一下什么是存储过程存储过程是利用SQL Server所提供的Tranact-SQL语言所编写的程序。Tranact-SQL语言是SQL Server提供专为设计数据库应用程序的语言,它是应用程序和SQL Server数据库间的主要程序式设计界面。它好比Oracle数据库系统中的Pro-SQL和Informix的数据库系统能够中的Informix-4GL语言一样。这类语言主要提供以下功能,让用户可以设计出符合引用需求的程序:1)、变量说明2)、ANSI兼容的SQL命令(如Select,Update….)3)、一般流程控制命令(if…else…、while….)4)、内部函数二、存储过程的书写格CREATE PROCEDURE [拥有者.]存储过程名[;程序编号][(参数#1,…参数#1024)][WITH{RECOMPILE | ENCRYPTION | RECOMPILE, ENCRYPTION}][FOR REPLICATION]AS 程序行其中存储过程名不能超过128个字。每个存储过程中最多设定1024个参数(SQL Server 7.0以上版本),参数的使用方法如下:@参数名 数据类型 [VARYING] [=内定值] [OUTPUT]每个参数名前要有一个“@”符号,每一个存储过程的参数仅为该程序内部使用,参数的类型除了IMAGE外,其他SQL Server所支持的数据类型都可使用。[=内定值]相当于我们在建立数据库时设定一个字段的默认值,这里是为这个参数设定默认值。[OUTPUT]是用来指定该参数是既有输入又有输出值的,也就是在调用了这个存储过程时,如果所指定的参数值是我们需要输入的参数,同时也需要在结果中输出的,则该项必须为OUTPUT,而如果只是做输出参数用,可以用CURSOR,同时在使用该参数时,必须指定VARYING和OUTPUT这两个语句。例子:CREATE PROCEDURE order_tot_amt @o_id int,@p_tot int output ASSELECT @p_tot = sum(Unitprice*Quantity)FROM orderdetailsWHERE ordered=@o_id例子说明:该例子是建立一个简单的存储过程order_tot_amt,这个存储过程根据用户输入的定单ID号码(@o_id),由定单明细表(orderdetails)中计算该定单销售总额[单价(Unitprice)*数量(Quantity)],这一金额通过@p_tot这一参数输出给调用这一存储过程的程序三、在SQL Server中执行存储过程在SQL Server的查询分析器中,输入以下代码:declare @tot_amt intexecute order_tot_amt 1,@tot_amt outputselect @tot_amt以上代码是执行order_tot_amt这一存储过程,以计算出定单编号为1的定单销售金额,我们定义@tot_amt为输出参数,用来承接我们所要的结果四、在ASP中调用存储过程<!-- 必须加载adovbs.inc文件,否则将出错 --><!--#include file="adovbs.inc"--><%dim objCnndim objCmddim Rsconst o_id=112'-----建立Connection对象----------set objCnn=Server.CreateObject("Adodb.connection")objCnn.Open "driver={sql server};server=localhost;uid=sa;pwd=cncanet;database=check;"'-----建立Command对象-----------set objCmd=Server.CreateObject("Adodb.Command")objCmd.ActiveConnection=objCnnobjCmd.CommandText="order_tot_amt" '指定存储过程名称objCmd.CommandType=adCmdStoredProc '其为Stored Procedure'-----准备stored procedure 的参数-------objCmd.Parameters.Append _objCmd.CreateParameter("o_id",adInteger,adParamInput,,o_id)objCmd.Parameters.Append _objCmd.CreateParameter("p_tot",adBigInt,adParamOutput,,0)'-----执行存储过程----------------------objCmd.Execute'-----输出参数以及处理结果--------------for each parm in objCmd.ParametersResponse.Write parm.name &"="& trim(parm) &""next%>
<% '用户输入非法字符 dim checkstring(3) checkstring(0) = "'" checkstring(1) = " " checkstring(2) = ";" checkstring(3) = ":"  '替换用户输入的非法字符 stringarray 非法字符数组 checkstring 需检查的字符串 function ReplaceString(stringarray,checkstring)   for i=0 to ubound(stringarray)   checkstring = Replace(checkstring,stringarray(i),"")  next    ReplaceString = checkstring   end function%>uid = ReplaceString(checkstring,Request.Form("loginname"))upwd = ReplaceString(checkstring,Request.Form("password"))
<%dim rsdim sqldim countset rs=server.createobject("adodb.recordset")sql = "select * from kml_sclass"rs.open sql,conn,1,1%><script language = "JavaScript">var onecount;onecount=0;subcat = new Array();        <%        count = 0        do while not rs.eof        %>subcat[<%=count%>] = new Array("<%= trim(rs("sclassname"))%>","<%= trim(rs("bclassid"))%>","<%= trim(rs("sclassid"))%>");        <%        count = count + 1        rs.movenext        loop        rs.close        %>onecount=<%=count%>;function changelocation(locationid)    {    document.myform.sclassid.length = 0;    var locationid=locationid;    var i;    for (i=0;i < onecount; i++)        {            if (subcat[i][1] == locationid)            {              document.myform.sclassid.options[document.myform.sclassid.length] = new Option(subcat[i][0], subcat[i][2]);            }               }           }   </script></head><body><br><form name="myform" method="post" action="?action=addsave"><table width="80%"  border="0" align="center" cellpadding="2" cellspacing="1" bgcolor="#CCCCCC">  <tr bgcolor="#F6F6F6">    <td height="25" colspan="2"><div align="center"><strong>修改新闻</strong></div></td>  </tr><tr bgcolor="#F6F6F6"><td align="center" height="25">新闻样式:</td><td><input name="jibie" type="radio" value="0" checked>          中文版</td></tr>  <tr>    <td width="15%" height="25" align="right" bgcolor="#F6F6F6">文章类型:</td>    <td width="85%" bgcolor="#FFFFFF"><%    sql = "select * from kml_bclass"    rs.open sql,conn,1,1 if rs.eof and rs.bof then response.write "请先添加栏目。" response.end else%><select name="bclassid" location(document.myform.bclassid.options[document.myform.bclassid.selectedIndex].value)" size="1">        <option selected value="<%=trim(rs("bclassid"))%>"><%=trim(rs("bclassname"))%></option>        <%dim selclass         selclass=rs("bclassid")        rs.movenext        do while not rs.eof%><option value="<%=trim(rs("bclassid"))%>"><%=trim(rs("bclassname"))%></option><%rs.movenextloopend ifrs.close%>      </select>      <select name="sclassid"><%sql="select * from kml_sclass where bclassid="&selclassrs.open sql,conn,1,1if not(rs.eof and rs.bof) then%>        <option selected value="<%=rs("sclassID")%>"><%=rs("sclassname")%></option><%rs.movenextdo while not rs.eof%><option <%if RsEdit("sclassid")=rs("sclassID") then %> selected <% end if %>value="<%=rs("sclassID")%>"><%=rs("sclassname")%></option><%rs.movenextloopend if        rs.close        set rs = nothing%></select>
Array()CInt()CStr()Date()DateAdd()Day()FormatCurrency()FormatDateTime()FormatNumber()FormatPercent()Instr()InstrRev()Int()IsArray()IsDate()IsNull()IsNumeric()IsObject()LBound()LCase()Len()LTrim()Mid()Minute()Month()Now()Right()Rnd()Round()Rtrim()Second()StrReverse()Time()Trim()UBound()VarType()WeekDay()WeekDayName()Year()MonthName()DateDiff()Hour()IsEmpty()Left()Split()UCase() ASP函数与VBSCRIPT类似,以下举一些常用的函数Array()函数返回一个数组表达式 Array(list)允许数据类型: 字符,数字均可实例:<%Dim myArray()For i = 1 to 7Redim Preserve myArray(i)myArray(i) = WeekdayName(i)Next%>返回结果: 建立了一个包含7个元素的数组myArraymyArray("Sunday","Monday", ... ... "Saturday")CInt()函数将一个表达式转化为数字类型表达式 CInt(expression)允许数据类型: 任何有效的字符均可实例:<%f = "234"response.write cINT(f) + 2%>返回结果: 236转化字符"234"为数字"234",如果字符串为空,则返回0值CreateObject()函数建立和返回一个已注册的ACTIVEX组件的实例。表达式 CreateObject(objName)允许数据类型: objName 是任何一个有效、已注册的ACTIVEX组件的名字.实例: <%Set con = Server.CreateObject("ADODB.Connection")%>CStr()函数转化一个表达式为字符串.表达式 CStr(expression)允许数据类型: expression 是任何有效的表达式。实例: <%s = 3 + 2response.write "The 返回结果 is: " & cStr(s)%>返回结果: 转化数字“5”为字符“5”。Date()函数返回当前系统日期.表达式 Date()允许数据类型: None.实例: <%=Date%>返回结果: 9/9/00DateAdd()函数返回一个被改变了的日期。表达式 DateAdd(timeinterval,number,date)允许数据类型:timeinterval is the time interval to add;number is amount of time intervals to add;and date is the starting date.实例: <%currentDate = #9/9/00#newDate = DateAdd("m",3,currentDate)response.write newDate%><%currentDate = #12:34:45 PM#newDate = DateAdd("h",3,currentDate)response.write newDate%>返回结果: 9/9/003:34:45 PM"m" = "month";"d" = "day";If currentDate is in time format then,"h" = "hour";"s" = "second";DateDiff()函数返回两个日期之间的差值 。表达式 DateDiff(timeinterval,date1,date2 [, firstdayofweek [, firstweekofyear]])允许数据类型: timeinterval 表示相隔时间的类型,如“M“表示“月”。实例: <%fromDate = #9/9/00#toDate = #1/1/2000#response.write "There are " & _DateDiff("d",fromDate,toDate) & _" days to millenium from 9/9/00."%>返回结果: 从9/9/00 到2000年还有 150 天.Day()函数返回一个月的第几日 .表达式 Day(date)允许数据类型: date 是任何有效的日期。实例: <%=Day(#9/9/00#)%>返回结果: 4FormatCurrency()函数返回表达式,此表达式已被格式化为货币值表达式 FormatCurrency(Expression [, Digit [, LeadingDigit [, Paren [, GroupDigit]]]])允许数据类型: Digit 指示小数点右侧显示位数的数值。默认值为 -1,指示使用的是计算机的区域设置; LeadingDigit 三态常数,指示是否显示小数值小数点前面的零。实例: <%=FormatCurrency(34.3456)%>返回结果: $34.35FormatDateTime()函数返回表达式,此表达式已被格式化为日期或时间表达式 FormatDateTime(Date, [, NamedFormat])允许数据类型: NamedFormat 指示所使用的日期/时间格式的数值,如果省略,则使用 vbGeneralDate.实例: <%=FormatDateTime("09/9/00", vbLongDate)%>返回结果: Sunday, September 09, 2000FormatNumber()函数返回表达式,此表达式已被格式化为数值.表达式 FormatNumber(Expression [, Digit [, LeadingDigit [, Paren [, GroupDigit]]]])允许数据类型: Digit 指示小数点右侧显示位数的数值。默认值为 -1,指示使用的是计算机的区域设置。; LeadingDigit i指示小数点右侧显示位数的数值。默认值为 -1,指示使用的是计算机的区域设置。; Paren 指示小数点右侧显示位数的数值。默认值为 -1,指示使用的是计算机的区域设置。; GroupDigit i指示小数点右侧显示位数的数值。默认值为 -1,指示使用的是计算机的区域设置。.实例: <%=FormatNumber(45.324567, 3)%>返回结果: 45.325FormatPercent()函数返回表达式,此表达式已被格式化为尾随有 % 符号的百分比(乘以 100 )。 (%)表达式 FormatPercent(Expression [, Digit [, LeadingDigit [, Paren [, GroupDigit]]]])允许数据类型: 同上.实例: <%=FormatPercent(0.45267, 3)%>返回结果: 45.267%Hour()函数以24时返回小时数.表达式 Hour(time)允许数据类型:实例: <%=Hour(#4:45:34 PM#)%>返回结果: 16(Hour has been converted to 24-hour system)Instr()函数返回字符或字符串在另一个字符串中第一次出现的位置.表达式 Instr([start, ] strToBeSearched, strSearchFor [, compare])允许数据类型: Start为搜索的起始值,strToBeSearched接受搜索的字符串 strSearchFor要搜索的字符.compare比较方式(详细见ASP常数)实例: <%strText = "This is a test!!"pos = Instr(strText, "a")response.write pos%>返回结果: 9InstrRev()函数同上,只是从字符串的最后一个搜索起表达式 InstrRev([start, ] strToBeSearched, strSearchFor [, compare])允许数据类型: 同上.实例: <%strText = "This is a test!!"pos = InstrRev(strText, "s")response.write pos%>返回结果: 13Int()函数返回数值类型,不四舍五入。表达式 Int(number)允许数据类型:实例: <%=INT(32.89)%>返回结果: 32IsArray()函数判断一对象是否为数组,返回布尔值 .表达式 IsArray(name)实例: <%strTest = "Test!"response.write IsArray(strTest)%>返回结果: FalseIsDate()函数判断一对象是否为日期,返回布尔值表达式 IsDate(expression)实例: <%strTest = "9/4/2000"response.write IsDate(strTest)%>返回结果: TrueIsEmpty()函数判断一对象是否初始化,返回布尔值.表达式 IsEmpty(expression)实例: <%Dim iresponse.write IsEmpty(i)%>返回结果: TrueIsNull()函数判断一对象是否为空,返回布尔值.表达式 IsNull(expression)实例: <%Dim iresponse.write IsNull(i)%>返回结果: FalseIsNumeric()函数判断一对象是否为数字,返回布尔值.表达式 IsNumeric(expression)实例: <%i = "345"response.write IsNumeric(i)%>返回结果: True就算数字加了引号,ASP还是认为它是数字。IsObject()函数判断一对象是否为对象,返回布尔值.表达式 IsObject(expression)实例: <%Set con = Server.CreateObject("ADODB.Connection")response.write IsObject(con)%>返回结果: TrueLBound()函数返回指定数组维的最小可用下标.表达式 Lbound(arrayname [, dimension])实例: <%i = Array("Monday","Tuesday","Wednesday")response.write LBound(i)%>返回结果: 0LCase()函数 返回字符串的小写形式表达式 Lcase(string)实例: <%strTest = "This is a test!"response.write LCase(strTest)%>返回结果: this is a test!Left()函数返回字符串左边第length个字符以前的字符(含第length个字符)
<%'For Each r In Request.QueryString If RegExpTest("[%<>s';]+",Request.QueryString) then  Response.Write("<script language='javascript'>alert('信息有误!');</script>")  Response.End() end If'Next'vbscript正则表达式测试方法 function RegExpTest(patrn, strng)  Dim regEx ' 建立变量。  Set regEx = New RegExp ' 建立正则表达式。  regEx.Pattern = patrn ' 设置模式。  regEx.IgnoreCase = False ' 设置是否区分大小写。  RegExpTest = regEx.Test(strng) ' 执行搜索测试。 end Function%>
下载AspJpeg v1.5.0.0,然后执行下载得到的文件,安装该组件。然后在ASP代码里增加一点点代码即可,增加的位置可以放在上传图片完成后,取得图片地址,进行修改。对于Z-Blog的使用者,直接将下面代码复制到c_system_lib.asp文件的TUpLoadFile类中的Upload函数的结尾即可实现水印功能。1、为图片加入水印功能Dim JpegSet Jpeg = Server.CreateObject("Persits.Jpeg")  ' 建立对象Jpeg.Open BlogPath & "/upload/" & FileName  ' 图片所在位置Jpeg.Canvas.Font.Color = &H000000 ' 颜色,这里是设置成:黑Jpeg.Canvas.Font.Family = "方正隶变简体"  ' 设置字体Jpeg.Canvas.Font.Bold = False '是否设置成粗体Jpeg.Canvas.Font.Size = 26 '字体大小Jpeg.Canvas.Font.Quality = 4 ' 文字清晰度Jpeg.Canvas.Print Jpeg.OriginalWidth/2-170,Jpeg.OriginalHeight-30, "WWW.WILLIAMLONG.INFO"   '水印文字Jpeg.Save BlogPath & "/upload/" & FileName  ' 保存文件Set Jpeg = Nothing2、为图片制作缩略图Dim JpegSet Jpeg = Server.CreateObject("Persits.Jpeg")  ' 建立对象Jpeg.Open BlogPath & "/upload/" & FileName  ' 图片所在位置Jpeg.Width = Jpeg.OriginalWidth / 2Jpeg.Height = Jpeg.OriginalHeight / 2' 设置缩略图大小(这里比例设定为50%),也可以给他准确的数值,比如Jpeg.Width=120Jpeg.Save BlogPath & "/upload/" & FileName  ' 保存文件Set Jpeg = Nothing
用法:1.Server.MapPath("/") 应用程序根目录所在的位置 如 C:Inetpubwwwroot2.Server.MapPath("./") 表示所在页面的当前目录    注:等价于Server.MapPath("") 返回 Server.MapPath("")所在页面的物理文件路径3.Server.MapPath("../")表示上一级目录4.Server.MapPath("~/")表示当前应用级程序的目录,如果是根目录,就是根目录,如果是虚拟目录,就是虚拟目录所在的位置 如:C:InetpubwwwrootExample注:等效于Server.MapPath("~")。语法:Server.MapPath(bstrLogicalPath)作用:将 bstrLogicalPath 映射为计算机上的物理目录,注意此物理目录可以也可能不存在。参数:bstrLogicalPath 的意思是相对目录*或虚拟目录。疑问:bstrLogicalPath 既然既可以表示相对目录,又可以表示虚拟目录,那么它什么时候表示相对目录,什么时候表示虚拟目录呢。规则:当 bstrLogicalPath 以 ../ 或 .. 开头时,当作相对目录。 <当 bstrLogicalPath 以斜杠开头( / 或 )时,从Web站点根目录(不是物理目录)的角度出发检查是否有匹配的虚拟目录(树)**,如果匹配,则当作虚拟目录,否则当作相对目录。当 bstrLogicalPath 不以斜杠开头( / 或 )时,从Web站点当前目录(不是物理目录)的角度出发检查是否有匹配的虚拟目录(树)**,如果匹配,则当作虚拟目录,否则当作相对目录。*也可以是文件。**由于虚拟目录下面可以再建立虚拟目录,所以这里使用虚拟目录树,即:每一层的目录或虚拟目录都要与 bstrLogicalPath 中的对应目录层匹配。***bstrLogicalPath 中含有英文点(.)或以斜杠结尾( / 或 )不影响上述规则。
生成静态页的好处不用说,当今大型网站,为缓解服务器端的压力许的的页面都改用了静态的页面,并利用AJAX技术动态地更新其中的部分内容,如广告等。一个简单的不用模板可以直接生成HTML静态页的方法.如一个正常的index.asp动态页面,新建一个文件 makeasp2html.asp<form method="post" action="">      <textarea name="asp2html" display:none"><!--#include file="index.asp"--></textarea>     <input type="submit" value="生成html页"/> </form> <% If request.Form("asp2html")<>"" then     filename="index.html"     set fso = Server.CreateObject("Scripting.FileSystemObject")     set fout = fso.CreateTextFile(server.mappath(""&filename&""))     fout.write request.form("asp2html")     fout.close     set fout=nothing     set fso=nothing end if %> 这样index.html文件就生成了,连模板都用不着,只要服务器要支持FSO,将正常情况下使用的ASP文件读取到textarea里就可以了。------------------------------------------------------------------------------------------------------细说一下常用的几种生成HTML的方法:生成HTML方法主要步骤只有两个:一、获取要生成的html文件的内容二、将获取的html文件内容保存为html文件我在这里主要说明的只是第一步:如何获取要生成的html文件的内容:目前常用获取html文件的内容的方法有几下几种:1、CODE: [Copy to clipboard] str="内容标记>"str=str&"内容标记>数据库读取内容....标记>....."这种方法与是在脚本内写要生成的html内容,不太方便预览生成页面的内容,无法可视化布局页面,更改html模板时会更加复杂。用这种方法的人很多,但我感觉这种方法是最不方便的。2、制作单独的HTML模板页,动态的内容用特定的字符作为标记(如:有人用$title$标记为网页标题),用ADODB.Stream或者Scripting.FileSystemObject将其模板内容载入,然后再用替换方法把原先定好的标记替换为动态内容(如:Replace(载入的模板内容,"$title$",rs("title" ) ) )。3、用XMLHTTP或serverXMLHTTP获取动态页所显示的HTML内容,CODE: [Copy to clipboard] 我常用的生成html文件的实例:'weburl是要获取的动态页地址'getHTTPPage(weburl)是获取动态页内容的函数weburl="http://"&Request.ServerVariables("SERVER_NAME")&"/contact.asp?id="&rs("id")&""‘指定动态页地址body=getHTTPPage(weburl)'用函数取到动态页地址的内容此方法最大的好处就是不用费力气专门去写静态的模板页面,只是将原来就有的动态页面转换为HTML静态页面,但生成速度不是太快。我常用的生成HTML的方法就是第3种:用XMLHTTP获取动态页生成的HTML内容,再用ADODB.Stream或者Scripting.FileSystemObject保存成html文件。第二步是生成文件的方法:ASP里常用的有用ADODB.Stream生成文件和Scripting.FileSystemObject生成文件两种1、Scripting.FileSystemObject生成文件方法:CODE: [Copy to clipboard] Set fso = CreateObject("Scripting.FileSystemObject")File=Server.MapPath("要生成文件路径和文件名.htm")Set txt=fso.OpenTextFile(File,8,True)  data1="文件内容"用WriteLine方法生成文件txt.WriteLine data1data2="文件内容"'用Write方法生成文件txt.Write data2txt.Closetxt.fso2、ADODB.Stream生成文件方法:CODE: [Copy to clipboard] Dim objAdoStreamset objAdoStream = Server.createObject("ADODB.Stream")objAdoStream.Type = 1objAdoStream.Open()objAdoStream.Write("文件内容")objAdoStream.SaveToFile 要生成文件路径和文件名.htm,2[next] objAdoStream.Close()再说一下我对HTML防采集却不防搜索引擎蜘蛛的一些经验:  我开发过几个采集程序,也研究过很多采集程序代码,所以对采集程序的原理还算是稍微有些了解。先说一下采集原理:采集程序的主要步骤如下:一、获取被采集的页面的内容二、从获取代码中提取所有用的数据一、获取被采集的页面的内容我目前所掌握的ASP常用获取被采集的页面的内容方法:1、用serverXMLHTTP组件获取数据CODE: [Copy to clipboard] Function GetBody(weburl)     '创建对象    Dim ObjXMLHTTP    Set ObjXMLHTTP=Server.CreateObject("MSXML2.serverXMLHTTP")    '请求文件,以异步形式    ObjXMLHTTP.Open "GET",weburl,False    ObjXMLHTTP.send    While ObjXMLHTTP.readyState <> 4        ObjXMLHTTP.waitForResponse 1000    Wend    '得到结果     GetBody=ObjXMLHTTP.responseBody    '释放对象     Set ObjXMLHTTP=NothingEnd Function调用方法:GetBody(文件的URLf地址) 2、或XMLHTTP组件获取数据CODE: [Copy to clipboard] Function GetBody(weburl)     '创建对象    Set Retrieval = CreateObject("Microsoft.XMLHTTP")     With Retrieval      .Open "Get", weburl, False, "", ""      .Send      GetBody = .ResponseBody     End With     '释放对象    Set Retrieval = Nothing End Function调用方法:GetBody(文件的URLf地址) 这样获取的数据内容还需要进行编码转换才可以使用CODE: [Copy to clipboard] 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 = nothingEnd Function调用方法:BytesToBstr(要转换的数据,编码)'编码常用为GB2312和UTF-8二、从获取代码中提取所有用的数据目前我掌握的方法有:1、用ASP内置的MID函数截取需要的数据CODE: [Copy to clipboard] Function body(wstr,start,over)start=Newstring(wstr,start)'设置需要处理的数据的唯一的开始标记over=Newstring(wstr,over)'和start相对应的就是需要处理的数据的唯一的结束标记body=mid(wstr,start,over-start)'设置显示页面的范围End Function调用方法:body(被采集的页面的内容,开始标记,结束标记)2、用正则获取需要的数据CODE: [Copy to clipboard] Function body(wstr,start,over)Set xiaoqi = New Regexp'设置配置对象xiaoqi.IgnoreCase = True'忽略大小写xiaoqi.Global = True'设置为全文搜索xiaoqi.Pattern =  "”&start&“.+?”&over&“"'正则表达式 Set Matches =xiaoqi.Execute(wstr)'开始执行配置[next] set  xiaoqi=nothing body=""For Each Match in Matchesbody=body&Match.Value '循环匹配Next  End Function调用方法:body(被采集的页面的内容,开始标记,结束标记)采集程序祥细思路:1、取得网站的分页列表页的每页地址目前绝大部分动态网站的分页地址都有规则,如:动态页第一页:index.asp?page=1第二页:index.asp?page=2第三页:index.asp?page=3.....静态页第一页:page_1.htm第二页:page_2.htm第三页:page_3.htm.....取得网站的分页列表页的每页地址,只需要用变量替代每页地址的变化的字符即可如:page_.htm2、获取被采集网站的分页列表页内容3、从分页列表代码中提取被采集的内容页面的URL连接地址绝大部分分页页面里的内容页连接也有固
set rsn=server.CreateObject("adodb.recordset")sqln="select top 1 * from vArticle where apage='"&abname&"'"rsn.open sqln,conn,1,1if not rsn.eof then'do while not rsn.eof'page_n=len(rsn("aContent"))-len(replace(rsn("aContent"),"[NextPage]",""))page_n=split(rsn("aContent"),"[NextPage]")for i=1 to Ubound(page_n)+1set rs=server.CreateObject("adodb.recordset")sql="select * from hy_moban where mname='资讯内页'"rs.open sql,conn,1,1okfile=rs("mcontent")rs.closeset rs=nothing'if i=1 then 'ppage=1 'else 'ppage=i-1 'end if 'if i=1 and page_n+1>i then 'npage=i+1 'else 'npage=page_n+1 'end ifaFrom=split(rsn("aFrom")&"|","|")if aFrom(0)="" thennaFrom="未知"elsenaFrom=aFrom(0)end ifk=i-1Ntitle=rsn("aTitle")&"|"&rsn("akeyword")okfile=replace(okfile,"$Ntitle$",Ntitle)okfile=replace(okfile,"$C_Title$",rsn("C_Title"))okfile=replace(okfile,"$aTitle$",rsn("aTitle"))okfile=replace(okfile,"$acount$",rsn("acount"))okfile=replace(okfile,"$aIntime$",rsn("aIntime"))okfile=replace(okfile,"$aFrom$",naFrom)okfile=replace(okfile,"$aContent$",page_n(k))okfile=replace(okfile,"$aInUser$",rsn("aInUser"))apage=replace(rsn("apage"),".shtml","")asetpage=""for j=1 to Ubound(page_n)+1if j=i thenasetpage=asetpage&"[<font color=red>"&i&"</font>]"elseif j=1 thenasetpage=asetpage&"[<a href="&rsn("apage")&">"&j&"</a>]"elseasetpage=asetpage&"[<a href="&apage&"-haowai-"&j&".shtml>"&j&"</a>]"end ifnext'asetpage="<br><a href="""&apage&"_"&ppage&".shtml"">上一页</a> <a href="""&apage&"_"&npage&".shtml"">下一页</a>"okfile=replace(okfile,"$aSetpage$",asetpage)myear=year(rsn("aInTime"))&"-"&month(rsn("aInTime"))if i=1 thenmypage=rsn("apage")elsemypage=apage&"-haowai-"&i&".shtml"end ifSet fso1 = Server.CreateObject("Scripting.FileSystemObject")  Set fout1 = fso1.Createtextfile(Server.MapPath("/"&"article/"&myear&"/"&mypage),true) fout1.writeline okfilefout1.close'rsn.movenext'loopnextend ifrsn.closeset rsn=nothing
dd = Date() '今天dd = dateadd("m",1,dd) '月份加1dd = Cdate(Year(dd) & "-" & Month(dd) & "-1") '下月的第一天dd=dateadd("d",dd,-1) '本月的最后一天dd=day(dd) '本月的天数Response.Write(dd)
随机产生N位由数字和字母组成的密码 asp随机数<%RandomizeDo While Len(pass)<12 ’随机密码位数num1=CStr(Chr((57-48)*rnd+48)) ’0~9num2=CStr(Chr((90-65)*rnd+65)) ’A~Znum3=CStr(Chr((122-97)*rnd+97)) ’a~zpass=pass&num1&num2&num3loop%><%=pass%>1、小于号的作用其实是小等于号的作用2、书上说产生某范围内随机数公式是(<上限>-<下限>+1)*rnd+<下限>但是实际运行的结果是:下限——上限+1(<上限>-<下限>)*rnd+<下限>才是正确的3、产生随机密码每3位为一组,第一位为数字,第二位为大写字母,第三位为小写字母,哪位高手能告诉我如何让随机数的位置也是随机的?<%sub sjs(n)    randomize    response.write int(rnd*n)end sub’n为随机数的最大值%>
ASP短信群发代码
 <form action="insert.asp" method="post" enctype="multipart/form-data" name="form1" onSubmit="b1_onclick()">  <table width="500" border="1" align="center" cellpadding="0" cellspacing="0">    <tr>      <td colspan="2" bgcolor="#999999" class="t">选择文件</td>    </tr>    <tr>      <td colspan="2" class="t">&nbsp;</td>    </tr>    <tr>      <td width="126" class="t">选择文件(excel)</td>      <td width="368" class="t"><label>        <input name="filexls" type="file" size="35">      </label></td>    </tr>    <tr>      <td colspan="2" class="t">        <label>        <input type="submit" name="Submit" value="导入数据">        </label>  <a href="1122.asp" class="t">返回</a>     </td>    </tr>  </table></form>   <!--#include virtual="/inc/clsdbctrl.asp"--><!--#include virtual="/inc/function.asp"--><%dim upfile_5xSoft_StreamClass upload_5xSoftdim Form,File,VersionPrivate Sub Class_Initializedim iStart,iFileNameStart,iFileNameEnd,iEnd,vbEnter,iFormStart,iFormEnd,theFiledim strDiv,mFormName,mFormValue,mFileName,mFileSize,mFilePath,iDivLen,mStrVersion="任翔专用上传程序"if Request.TotalBytes<1 then Exit Subset Form=CreateObject("Scripting.Dictionary")set File=CreateObject("Scripting.Dictionary")set upfile_5xSoft_Stream=CreateObject("Adodb.Stream")upfile_5xSoft_Stream.mode=3upfile_5xSoft_Stream.type=1upfile_5xSoft_Stream.openupfile_5xSoft_Stream.write Request.BinaryRead(Request.TotalBytes)vbEnter=Chr(13)&Chr(10)iDivLen=inString(1,vbEnter)+1strDiv=subString(1,iDivLen)iFormStart=iDivLeniFormEnd=inString(iformStart,strDiv)-1while iFormStart < iFormEndiStart=inString(iFormStart,"name=""")iEnd=inString(iStart+6,"""")mFormName=subString(iStart+6,iEnd-iStart-6)iFileNameStart=inString(iEnd+1,"filename=""")if iFileNameStart>0 and iFileNameStart<iFormEnd theniFileNameEnd=inString(iFileNameStart+10,"""")mFileName=subString(iFileNameStart+10,iFileNameEnd-iFileNameStart-10)iStart=inString(iFileNameEnd+1,vbEnter&vbEnter)iEnd=inString(iStart+4,vbEnter&strDiv)if iEnd>iStart thenmFileSize=iEnd-iStart-4elsemFileSize=0end ifset theFile=new FileInfotheFile.FileName=getFileName(mFileName)theFile.FilePath=getFilePath(mFileName)theFile.FileSize=mFileSizetheFile.FileStart=iStart+4theFile.FormName=FormNamefile.add mFormName,theFileelseiStart=inString(iEnd+1,vbEnter&vbEnter)iEnd=inString(iStart+4,vbEnter&strDiv)if iEnd>iStart thenmFormValue=subString(iStart+4,iEnd-iStart-4)elsemFormValue=""end ifform.Add mFormName,mFormValueend ifiFormStart=iformEnd+iDivLeniFormEnd=inString(iformStart,strDiv)-1wendEnd SubPrivate Function subString(theStart,theLen)dim i,c,stempupfile_5xSoft_Stream.Position=theStart-1stemp=""for i=1 to theLenif upfile_5xSoft_Stream.EOS then Exit forc=ascB(upfile_5xSoft_Stream.Read(1))If c > 127 Thenif upfile_5xSoft_Stream.EOS then Exit forstemp=stemp&Chr(AscW(ChrB(AscB(upfile_5xSoft_Stream.Read(1)))&ChrB(c)))i=i+1elsestemp=stemp&Chr(c)End IfNextsubString=stempEnd functionPrivate Function inString(theStart,varStr)dim i,j,bt,theLen,strInString=0Str=toByte(varStr)theLen=LenB(Str)for i=theStart to upfile_5xSoft_Stream.Size-theLenif i>upfile_5xSoft_Stream.size then exit Functionupfile_5xSoft_Stream.Position=i-1if AscB(upfile_5xSoft_Stream.Read(1))=AscB(midB(Str,1)) thenInString=ifor j=2 to theLenif upfile_5xSoft_Stream.EOS theninString=0Exit forend ifif AscB(upfile_5xSoft_Stream.Read(1))<>AscB(MidB(Str,j,1)) thenInString=0Exit Forend ifnextif InString<>0 then Exit Functionend ifnextEnd FunctionPrivate Sub Class_Terminateform.RemoveAllfile.RemoveAllset form=nothingset file=nothingupfile_5xSoft_Stream.closeset upfile_5xSoft_Stream=nothingEnd SubPrivate function GetFilePath(FullPath)If FullPath <> "" ThenGetFilePath = left(FullPath,InStrRev(FullPath, ""))ElseGetFilePath = ""End IfEnd functionPrivate function GetFileName(FullPath)If FullPath <> "" ThenGetFileName = mid(FullPath,InStrRev(FullPath, "")+1)ElseGetFileName = ""End IfEnd functionPrivate function toByte(Str)dim i,iCode,c,iLow,iHightoByte=""For i=1 To Len(Str)c=mid(Str,i,1)iCode =Asc(c)If iCode<0 Then iCode = iCode + 65535If iCode>255 TheniLow = Left(Hex(Asc(c)),2)iHigh =Right(Hex(Asc(c)),2)toByte = toByte & chrB("&H"&iLow) & chrB("&H"&iHigh)ElsetoByte = toByte & chrB(AscB(c))End IfNextEnd functionEnd ClassClass FileInfodim FormName,FileName,FilePath,FileSize,FileStartPrivate Sub Class_InitializeFileName = ""FilePath = ""FileSize = 0FileStart= 0FormName = ""End SubP
URL重写-rewrite.zip
<!--#include file="../inc/conn.asp"--><%Call opendata(1)Set rs=server.CreateObject("adodb.recordset")xmlfile=server.mappath("content.xml")Set fso = CreateObject("Scripting.FileSystemObject")Set MyFile = fso.CreateTextFile(xmlfile,True,-1)MyFile.WriteLine("<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes""?>")MyFile.WriteLine("<content Name=""新闻动态"">")rs.open "select * from detail where classid=268 order by updatetime desc",conn,1,1if not rs.eof thendo while not rs.eof MyFile.WriteLine("<article Thumb=""news/thumb4.jpg"" Large =""news/large4.jpg"">") MyFile.WriteLine("<headline>xx竹立方竹艺臻品馆开馆</headline>") MyFile.WriteLine("<date>2010/05/01</date>") MyFile.WriteLine("<copy_intro><![CDATA[竹立方,来自竹林深处的清新气息,来自时代低碳环保的呼唤,来自健康时尚的现代生活理念。]]></copy_intro>") MyFile.WriteLine("<copy_full><![CDATA[    竹立方,来自竹林深处的清新气息,来自时代低碳环保的呼唤,来自健康时尚的现代生活理念。<br><br>    竹立方——竹艺臻品馆,主要经营竹炭、竹纤维、竹家具、竹工艺品等,与最具实力的厂家合作,提供一手货源,为广大追求现代都市时尚生活的人提供低碳环保的竹产品。<br><br>     一想到竹,便想到那份翠绿。竹子,从竹竿,竹笋到竹纤维,竹地板,竹炭,从以其虚心谦恭的品格,默默无闻地做出贡献。而其独特的品质,自身的特性,发展前景不可限量。<br><br>    来竹立方,感受竹子带来的那份美妙神奇吧!]]></copy_full>") MyFile.WriteLine("<copy_pic><![CDATA[竹立方]]></copy_pic>") MyFile.WriteLine("</article>")rs.movenextloopend ifrs.closeMyFile.WriteLine("</content>")MyFile.Close%>  最近研究asp生成xml文件,发现如果生成文件里面出现中文的话,xml文件就是乱码。在网上找了一下,说的都是把页面,xml都设置成统一的编码等等,但是都没有解决问题。原因:后来发现原来是fso的问题:fso不支持utf-8。解决办法:Set MyFile = fso.CreateTextFile(xmlfile,True,-1)  这句的第三个参数就非常重要-1是boolean值的true; 拓展:下面是对CreateTextFile的参数的详细说明:object.CreateTextFile(filename[, overwrite[, unicode]])参数object必选项。应为 FileSystemObject 或 Folder 对象的名称。filename必选项。指明所要创建文件的字符串表达式。overwrite可选项。Boolean 值,指明能否覆盖已有文件。如果文件可以覆盖,则值为 true ,否则为 false。如果忽略,则已有文件不能被覆盖。unicode可选项。Boolean 值,指明文件是否以 Unicode 或 ASCII 文件方式创建。如果文件作为 Unicode 文件创建,则值为 true ,如果作为 ASCII 文件创建,则为 false。如果忽略,则假定为 ASCII 文件。 范例代码:<%xmlfile=server.mappath("media.xml")Set fso = CreateObject("Scripting.FileSystemObject")Set MyFile = fso.CreateTextFile(xmlfile,True,-1)MyFile.WriteLine("<?xml version=""1.0"" encoding=""UTF" & "-8""?>")MyFile.WriteLine("<settings autoRotate=""1"" autoRotateSpeed=""4""  useSubtitle=""0"" useTooltip=""1""   useSecondCaption=""1""   spanX=""400""  spanY=""40""  centerX=""500"" centerY=""300""  distanceValue=""0""  perspectiveRatio=""0.5""  minimumscale="".1"" turningspeed=""4""  rotationKind=""1""  useFocalBlur=""1""  focalBlurValue="".6""  useMotionBlur=""1""   motionBlurValue="".25""  useFadeOnMouseOver=""1""  mouseOverAlphaValue="".5"" useReflection=""1""   reflectionAlphaValue="".5""")MyFile.WriteLine(" />")%><%MyFile.WriteLine("<photos>")%><%MyFile.WriteLine("<photo imageURL=""空调打孔"" linkData=""http://www.kongtiaodakong.com/"" linkType=""frameNumber"" linkTarget=""carousel"" captionText=""陈瑞"" captionText2=""陈瑞"" enableButtonWhenInFront=""1"" />")%><%MyFile.WriteLine("</photos>")%><%MyFile.Close%>