You are on page 1of 11

50 bài tập ASP cho người mới bắt đầu

Bộ bài tập ASP cơ bản, gồm 50 bài, từng bước từng bước, tương đối dễ học. Mong các bạn sưu
tầm tiếp và cập nhật thêm, để bộ sưu tập này nhiều lên và hữu ích hơn.
---------------------------
Băng qua việc cài đặt trình IIS trong WINDOWS, tạo thư mục ViduASP và soạn thảo các bài tập
vào đó, Share thư mục ViduASP thành WEB bằng cách chọn WebSharing. Cuối cùng có thể
chạy bằng địa chỉ trên Address của IE là http://localhost/viduAsp/tenfile.asp
Next
%>

Phần I: ASP cơ bản </body>


</html>
1. Ghi dòng text ra trang web
5. Ví dụ về vòng lặp<html>
<html> <body>
<body> <%
<% response.write("Hello World!") dim i
%> for i=1 to 6
</body> response.write("<h" & i & ">Header " & i
</html> & "</h" & i & ">")
next
2. Định dạng text kết hợp với các thẻ %>
html<html> </body>
<body> </html>
<% response.write("<h2>You can use
HTML tags to format the text!</h2>") %> 6. Câu lệnh If và hàm thời gian dạng
<% đơn giản<html>
response.write("<p <body>
style='color:#0000ff'>This text is styled <%
with the style attribute!</p>") dim h
%> h=hour(now())
</body> response.write("<p>" & now())
</html> response.write(" (Norwegian Time) </p>")
If h<12 then
3. Định nghĩa biến trong Asp response.write("Good Morning!")
<html> else
<body> response.write("Good day!")
<% end if
dim name %>
name="Donald Duck" </body>
response.write("My name is: " & name) </html>
%>
</body> 7. Sử dụng lồng JavaScript (đối tượng
</html> Date trong JavaScript)
<%@ language="javascript" %>
4. Định nghĩa một dãy <html>
<html> <body>
<body> <%
<% var d=new Date()
Dim famname(6),i var h=d.getHours()
famname(1) = "Jan Egil" Response.Write("<p>")
famname(2) = "Tove" Response.Write(d + " (Norwegian Time)")
famname(3) = "Hege" Response.Write("</p>")
famname(4) = "Stale" if (h<12)
famname(5) = "Kai Jim" {
famname(6) = "Borge" Response.Write("Good Morning!")
}
For i = 1 to 6 else
response.write(famname(i) & "<br />") {
Response.Write("Good day!")
} </html>
%>
</body> 10. Tìm ra 1 ngày cụ thể sau ngày hiện
</html> tại một số ngày nào đó (ví dụ 30 ngày)
<html>
8. Date và Time trong VbScript <body>
<html> <%
<body> response.write(DateAdd("d",30,date()))
Today's date is: <%response.write(date()) %>
%>. <p>
<br> Syntax for DateAdd:
The server's local time is: < DateAdd(interval,number,date). You can use
%response.write(time())%>. <b>DateAdd</b> to for example calculate
</body> a date 30 days from today.
</html> </p>
</body>
9. Tính số ngày, tháng, năm từ năm </html>
hiện tại cho đến năm 3000
<html> 11. Định dạng ngày tháng theo các
<body> dạng khác nhau. Ví dụ này rất cần cho
<p>Countdown to year 3000:</p> các ứng dụng web xử lý ngày tháng
<p> như ngày sinh, ngày thi, ngày lên
<%millennium=cdate("1/1/3000 00:00:00") lương…
%> <html>
It is <body>
<%response.write(DateDiff("yyyy", Now(), <%
millennium))%> response.write(FormatDateTime(date(),vbg
years to year 3000! eneraldate))
<br> response.write("<br />")
It is response.write(FormatDateTime(date(),vblo
<%response.write(DateDiff("m", Now(), ngdate))
millennium))%> response.write("<br />")
months to year 3000! response.write(FormatDateTime(date(),vbsh
<br> ortdate))
It is response.write("<br />")
<%response.write(DateDiff("ww", Now(), response.write(FormatDateTime(now(),vblo
millennium))%> ngtime))
weeks to year 3000! response.write("<br />")
<br> response.write(FormatDateTime(now(),vbsh
It is orttime))
<%response.write(DateDiff("d", Now(), %>
millennium))%> <p>
days to year 3000! Syntax for FormatDateTime:
<br> FormatDateTime(date,namedformat).
It is </p>
<%response.write(DateDiff("h", Now(), </body>
millennium))%> </html>
hours to year 3000!
<br> 12. Kiểm tra xem 1 hằng số dạng ngày
It is có phải là 1ngày đúng không.
<%response.write(DateDiff("n", Now(), <html>
millennium))%> <body>
minutes to year 3000! <%
<br> somedate="10/30/99"
It is response.write(IsDate(somedate))
<%response.write(DateDiff("s", Now(), %>
millennium))%> </body>
seconds to year 3000! </html>
</p>
</body> Các hàm về xâu ký tự
13. Hàm chuyển đổi chữ thường ßà chữ %>
hoa </body>
<html> </html>
<body>
<% 18. Trích xâu con từ một xâu đã cho
name = "Bill Gates"
response.write(ucase(name)) <html>
response.write("<br>") <body>
response.write(lcase(name)) <%
%> sometext="Welcome to this Web"
</body> response.write(Left(sometext,5))
</html> response.write("<br>")
response.write(Right(sometext,5))
14. Các hàm huỷ bỏ dấu cách khi làm %>
việc với xâu ký tự </body>
<html> </html>
<body>
<% 19. Thay thế một từ trong 1 câu
name = " W3Schools " <html>
response.write("visit" & name & "now<br <body>
/>") <%
response.write("visit" & trim(name) & sometext="Welcome to this Web!!"
"now<br />") response.write(Replace(sometext, "Web",
response.write("visit" & ltrim(name) & "Page"))
"now<br />") %>
response.write("visit" & rtrim(name) & </body>
"now") </html>
%>
</body> 20. Trích một xâu con từ một xâu
</html> <html>
<body>
15. Đảo ngược xâu
<html> <%
<body> sometext="Welcome to this Web!!"
<% response.write(Mid(sometext, 9, 2))
sometext = "Hello Everyone!" %>
response.write(strReverse(sometext)) </body>
%> </html>
</body>
</html> Các lệnh liên quan đến thủ tục chương
trình con
16. Làm tròn số như thế nào? 21. Gọi thủ tục con viết theo kiểu
<html> VbScript khi lập trình ASP
<body> <html>
<% <head>
i = 48.66776677 <%
j = 48.3333333 sub vbproc(num1,num2)
response.write(Round(i)) response.write(num1*num2)
response.write("<br>") end sub
response.write(Round(j)) %>
%> </head>
</body> <body>
</html> <p>
You can call a procedure like this:
17. Tạo ra một số ngẫu nhiên </p>
<html> <p>
<body> Result: <%call vbproc(3,4)%>
<% </p>
randomize() <p>
response.write(rnd()) Or, like this:
</p> <input type="submit" value="Submit" />
<p> </form>
Result: <%vbproc 3,4%> <%
</p> dim fname
</body> fname=Request.QueryString("fname")
</html> If fname<>"" Then
Response.Write("Hello " & fname & "!
22. Gọi 1 thủ tục viết bằng JavaScript <br />")
khi lập trình Asp Response.Write("How are you today?")
<%@ language="javascript" %> End If
<html> %>
<head> </body>
<% </html>
function jsproc(num1,num2)
{ 25. Lấy giá trị từ form ra biến
Response.Write(num1*num2) <html>
} <body>
%> <form action="demo_simpleform.asp"
</head> method="post">
Your name: <input type="text"
<body> name="fname" size="20" />
<p> <input type="submit" value="Submit" />
Result: <%jsproc(3,4)%> </form>
</p> <%
</body> dim fname
</html> fname=Request.Form("fname")
If fname<>"" Then
23. Một sự so sánh giữa hai cách gọi Response.Write("Hello " & fname & "!
chương trình con từ VbScript và <br />")
JavaScript Response.Write("How are you today?")
<html> End If
<head> %>
<% </body>
sub vbproc(num1,num2) </html>
Response.Write(num1*num2)
end sub 26. Tương tác với người dùng dùng
%> trên form sử dụng Option radio
<script language="javascript" <html>
runat="server"> <%
function jsproc(num1,num2) dim cars
{ cars=Request.Form("cars")
Response.Write(num1*num2) %>
} <body>
</script> <form action="demo_radiob.asp"
</head> method="post">
<body> <p>Please select your favorite car:</p>
<p>Result: <%call vbproc(3,4)%></p> <input type="radio" name="cars"
<p>Result: <%call jsproc(3,4)%></p> <%if cars="Volvo" then
</body> Response.Write("checked")%>
</html> value="Volvo">Volvo</input>
<br />
Các xử lý trên form <input type="radio" name="cars"
24. Kiểm tra giá trị của một ô dữ liệu <%if cars="Saab" then
trên form Response.Write("checked")%>
<html> value="Saab">Saab</input>
<body> <br />
<form action="demo_reqquery.asp" <input type="radio" name="cars"
method="get"> <%if cars="BMW" then
Your name: <input type="text" Response.Write("checked")%>
name="fname" size="20" /> value="BMW">BMW</input>
<br /><br /> <input type="submit" value="Go!">
<input type="submit" value="Submit" /> </form>
</form> </body>
<% </html>
if cars<>"" then
Response.Write("<p>Your favorite car is: 29. Xử lý thông tin của form ngay tại
" & cars & "</p>") form
end if
%> <html>
</body> <body>
</html> <form action="demo_reqquery.asp"
method="get">
27. Sử dụng cookies để đếm số lần truy Your name: <input type="text"
cập vào website name="fname" size="20" />
<html> <input type="submit" value="Submit" />
<body> </form>
<% <%
dim numvisits dim fname
response.cookies("NumVisits").Expires=dat fname=Request.QueryString("fname")
e+365 If fname<>"" Then
numvisits=request.cookies("NumVisits") Response.Write("Hello " & fname & "!
if numvisits="" then <br />")
response.cookies("NumVisits")=1 Response.Write("How are you today?")
response.write("Welcome! This is the first End If
time you are visiting this Web page.") %>
else </body>
response.cookies("NumVisits")=numvisits </html>
+1
response.write("You have visited this ") 30. Lấy thông tin từ máy chủ
response.write("Web page " & numvisits)
if numvisits=1 then <html>
response.write " time before!" <body>
else <p>
response.write " times before!" <b>You are browsing this site with:</b>
end if <
end if %Response.Write(Request.ServerVariables("
%> http_user_agent"))%>
</body> </p>
</html> <p>
<b>Your IP address is:</b>
28. Hướng người dùng đến các form <
khác nhau khi người dùng lựa chọn %Response.Write(Request.ServerVariables("
hướng sử dụng remote_addr"))%>
<% </p>
if Request.Form("select")<>"" then <p>
Response.Redirect(Request.Form("selec <b>The DNS lookup of the IP address
t")) is:</b>
end if <
%> %Response.Write(Request.ServerVariables("
remote_host"))%>
<html> </p>
<body> <p>
<form action="demo_redirect.asp" <b>The method used to call the page:</b>
method="post"> <
<input type="radio" name="select" %Response.Write(Request.ServerVariables("
value="demo_server.asp"> request_method"))%>
Server Example<br> </p>
<input type="radio" name="select" <p>
value="demo_text.asp"> <b>The server's domain name:</b>
Text Example<br><br>
< end if
%Response.Write(Request.ServerVariables(" %>
server_name"))%> <html>
</p> <body>
<p> </body>
<b>The server's port:</b> </html>
<
%Response.Write(Request.ServerVariables(" 33. Kiểm tra xem bạn gửi 1 thông tin
server_port"))%> đến máy chủ hết bao nhiêu bộ nhớ
</p> (đơn vị tính bytes)
<p> <html>
<b>The server's software:</b> <body>
<
%Response.Write(Request.ServerVariables(" <form action="demo_totalbytes.asp"
server_software"))%> method="post">
</p> Please type something:
<input type="text" name="txt"><br><br>
</body> <input type="submit" value="Submit">
</html> </form>

<%
31. Lấy thông tin từ máy chủ If Request.Form("txt")<>"" Then
Response.Write("You submitted: ")
<html> Response.Write(Request.Form)
<body> Response.Write("<br><br>")
Response.Write("Total bytes: ")
<p> Response.Write(Request.Totalbytes)
All possible server variables: End If
</p> %>
<%
For Each Item in Request.ServerVariables </body>
Response.Write(Item & "<br />") </html>
Next
%> 34. Kiểm tra xem 1 file nào đó bị thay
đổi lần cuối là khi nào?
</body>
</html> <html>
<body>
32. Kiểm tra xem bạn đăng nhập trang
web lần đầu tiên hay bao nhiêu? <%
<% Set fs =
dim numvisits Server.CreateObject("Scripting.FileSystemO
response.cookies("NumVisits").Expires=dat bject")
e+365 Set rs =
numvisits=request.cookies("NumVisits") fs.GetFile(Server.MapPath("demo_lastmodifi
ed.asp"))
if numvisits="" then modified = rs.DateLastModified
response.cookies("NumVisits")=1 %>
response.write("Welcome! This is the first This file was last modified on: <
time you are visiting this Web page.") %response.write(modified)
else Set rs = Nothing
response.cookies("NumVisits")=numvisits Set fs = Nothing
+1 %>
response.write("You have visited this ")
response.write("Web page " & numvisits) </body>
if numvisits=1 then </html>
response.write " time before!"
else
response.write " times before!" 35. Mở 1 file text để đọc nội dung
end if <html>
<body> 37. Kiểm tra xem 1 tên file nào đó kể
cả đường dẫn có tồn tại hay không?
<%
Set FS = <html>
Server.CreateObject("Scripting.FileSystemO <body>
bject")
Set RS = <%
FS.OpenTextFile(Server.MapPath("text") & Set
"\TextFile.txt",1) fs=Server.CreateObject("Scripting.FileSyste
While not rs.AtEndOfStream mObject")
Response.Write RS.ReadLine
Response.Write("<br />") If
Wend (fs.FileExists("c:\winnt\cursors\3dgarro.cur")
%> )=true Then
Response.Write("File
<p> c:\winnt\cursors\3dgarro.cur exists.")
<a href="text/textfile.txt"><img Else
border="0" Response.Write("File
src="/images/btn_view_text.gif"></a> c:\winnt\cursors\3dgarro.cur does not
</p> exist.")
End If
</body>
</html> set fs=nothing
%>
36. Kiểm tra xem 1 file nào đó được mở
ra bao nhiêu lần </body>
<% </html>
Set
FS=Server.CreateObject("Scripting.FileSyste 38. Kiểm tra xem 1 thư mục nào đó có
mObject") tồn tại thực sự hay không?
Set
RS=FS.OpenTextFile(Server.MapPath("count <html>
er.txt"), 1, False) <body>
fcount=RS.ReadLine <%
RS.Close Set
fs=Server.CreateObject("Scripting.FileSyste
fcount=fcount+1 mObject")

'This code is disabled due to the write If fs.FolderExists("c:\temp") = true Then


access security on our server: Response.Write("Folder c:\temp exists.")
'Set Else
RS=FS.OpenTextFile(Server.MapPath("count Response.Write("Folder c:\temp does
er.txt"), 2, False) not exist.")
'RS.Write fcount End If
'RS.Close
set fs=nothing
Set RS=Nothing %>
Set FS=Nothing
</body>
%> </html>
<html>
<body> 39. Kiểm tra xem 1 ổ đĩa có tồn tại hay
<p> không?
This page has been visited <%=fcount%> <html>
times. <body>
</p> <%
</body> Set
</html> fs=Server.CreateObject("Scripting.FileSyste
mObject")
if fs.driveexists("c:") = true then %>
Response.Write("Drive c: exists.")
Else </body>
Response.Write("Drive c: does not </html>
exist.")
End If Chủ đề về text
42. Mở và đọc 1 file Text
Response.write("<br>") <html>
<body>
if fs.driveexists("g:") = true then <p>This is the text in the text file:</p>
Response.Write("Drive g: exists.") <%
Else Set
Response.Write("Drive g: does not fs=Server.CreateObject("Scripting.FileSyste
exist.") mObject")
End If
Set
set fs=nothing f=fs.OpenTextFile(Server.MapPath("testread
%> .txt"), 1)
Response.Write(f.ReadAll)
</body> f.Close
</html>
Set f=Nothing
40. Lấy ra tên thư mục của đường dẫn Set fs=Nothing
đã cho %>
</body>
<html> </html>
<body>
43.Lấy ra mấy ký tự từ 1 file text
<% <html>
Set <body>
fs=Server.CreateObject("Scripting.FileSyste <p>This is the first five characters from the
mObject") text file:</p>
p=fs.GetParentFolderName("c:\winnt\cursor
s\3dgarro.cur") <%
Set
Response.Write("The parent folder name of fs=Server.CreateObject("Scripting.FileSyste
c:\winnt\cursors\3dgarro.cur is: " & p) mObject")

set fs=nothing Set


%> f=fs.OpenTextFile(Server.MapPath("testread
.txt"), 1)
</body> Response.Write(f.Read(5))
</html> f.Close

41. Lấy ra phần mở rộng của 1 tên file Set f=Nothing


Set fs=Nothing
<html> %>
<body>
</body>
<% </html>
Set
fs=Server.CreateObject("Scripting.FileSyste 44.Đọc ra 1 dòng của 1 file text
mObject")
<html>
Response.Write("The file extension of the <body>
file 3dgarro is: ") <p>This is the first line of the text file:</p>
Response.Write(fs.GetExtensionName("c:\wi
nnt\cursors\3dgarro.cur")) <%

set fs=nothing
Set
fs=Server.CreateObject("Scripting.FileSyste Set f=Nothing
mObject") Set fs=Nothing
%>
Set
f=fs.OpenTextFile(Server.MapPath("testread 47. File được tạo ra lúc nào
.txt"), 1)
Response.Write(f.ReadLine) <html>
f.Close <body>

Set f=Nothing <%


Set fs=Nothing dim fs, f
%> set
fs=Server.CreateObject("Scripting.FileSyste
</body> mObject")
</html> set
f=fs.GetFile(Server.MapPath("testread.txt"))
45. Đọc tất cả các dòng của 1 file Text Response.Write("The file testread.txt was
<html> created on: " & f.DateCreated)
<body> set f=nothing
<p>This is all the lines in the text file:</p> set fs=nothing
%>
<%
Set </body>
fs=Server.CreateObject("Scripting.FileSyste </html>
mObject")
Set
f=fs.OpenTextFile(Server.MapPath("testread
.txt"), 1) Phần 2: ASP cơ sở dữ liệu
1. File modulieu.asp
do while f.AtEndOfStream = false <%
Response.Write(f.ReadLine) Set Conn =
Response.Write("<br>") Server.CreateObject("ADODB.Connection")
loop DSNStatement = "DRIVER=Microsoft Access
Driver (*.mdb);DBQ="
f.Close DSNStatement = DSNStatement &
Set f=Nothing Server.MapPath("/t36/database/thanhvien.m
Set fs=Nothing db")
%> Conn.Open DSNStatement
%>
</body>
</html> 2. Duyệt dữ liệu
<%@Language=VBScript%>
46. Bỏ qua 1 phần nào đó của file Text <!--#Include file="modulieu.asp"-->
<html> <HTML>
<body> <HEAD>
<p>The first four characters in the text file <meta name="GENERATOR"
are skipped:</p> content="Microsoft FrontPage 5.0">
<meta name="ProgId"
<% content="FrontPage.Editor.Document">
Set <META content=en http-equiv=Content-
fs=Server.CreateObject("Scripting.FileSyste Language>
mObject") <meta http-equiv="Content-Type"
content="text/html; charset=Unicode">
Set
f=fs.OpenTextFile(Server.MapPath("testread <TITLE></TITLE>
.txt"), 1) </HEAD>
f.Skip(4) <BODY>
Response.Write(f.ReadAll) <font size=5>
f.Close
<% Response.write "Chủ đề :" & rs("Loai") &
Select case weekday(date()) "<br>"
case 1 Response.write "Nội dung :" & rs("NoiDung")
thu = "Chủ Nhật" & "<br>"
case 2
thu="Thứ Hai" Response.write "</Pre>"
case 3 Response.write "</TD>"
thu="Thứ Ba" Response.write "</TR>"
case 4 rs.moveNext
thu="Thứ Tư" Loop
case 5 Response.write "</Table>"
thu="Thứ Năm"
case 6 %>
thu="Thứ Sáu" <P>&nbsp;</P>
case 7
thu="Thứ Bảy" </BODY>
end Select </HTML>
ngay=day(date())
thang=month(date()) 3. Sửa dữ liệu
nam=year(date()) <%@Language=VBScript%>
<!--#Include file="modulieu.asp"-->
Response.Write Thu & ", Ngày: " & <HTML>
cstr(ngay) & " Tháng " & cstr(thang) & " <HEAD>
Nam " & cstr(Nam) & "<br>" & "<br>" <meta name="GENERATOR"
%> content="Microsoft FrontPage 5.0">
</font> <meta name="ProgId"
</center> content="FrontPage.Editor.Document">
<% <META content=en http-equiv=Content-
Dim Conn, RS 'Declares the Conn Language>
(Connection) and RS (Recordset) variables <meta http-equiv="Content-Type"
content="text/html; charset=Unicode">
Set RS = <TITLE></TITLE>
Server.CreateObject("ADODB.Recordset") </HEAD>
SQLStatement = "SELECT * FROM hoidap" <BODY>
RS.Open SQLStatement, Conn, 3, 3 <font size=5>
<%
Select case weekday(date())
case 1
rs.movefirst thu = "Chủ Nhật"
Response.Write "<center>" & "<h3>" & case 2
"<font color=red>" & "Danh sách các câu thu="Thứ Hai"
hỏi thảo luận" & "</font>" & "</h3>" & case 3
"</center>" thu="Thứ Ba"
kt=0 case 4
Response.Write "<Table border=0>" thu="Thứ Tư"
Do while not rs.eof case 5
Response.write "<TR>" thu="Thứ Năm"
if kt=1 then case 6
Response.write "<TD bgcolor=Pink>" thu="Thứ Sáu"
kt=0 case 7
else thu="Thứ Bảy"
Response.write "<TD bgcolor=Yellow>" end Select
kt=1 ngay=day(date())
end if thang=month(date())
Response.write "<Pre>" nam=year(date())
Response.write "<font color=Blue>" &
"Nguoi gui :" & "</font>" & rs("FromUser")
& "<br>"
Response.write "Thời gian :" & rs("ngay") &
" - " & rs("thoigian") & "<br>"
Response.Write Thu & ", Ngày: " &
cstr(ngay) & " Tháng " & cstr(thang) & "
Nam " & cstr(Nam) & "<br>" & "<br>"
%>
</font>
</center>
<%
bTenDangNhap=Request("TenDangNhap")
bhoten=request("hoten")
bmatkhau=request("matkhau")
bdiachi=request("diachi")
bdienthoai=request("dienthoai")
bemail=request("email")

Set RS =
Server.CreateObject("ADODB.Recordset")
SQLStatement = "SELECT * FROM hoso
WHERE TenDangNhap='"& bTenDangNhap
&"' and MatKhau='"& bMatKhau &"'"
RS.Open SQLStatement, Conn, 3, 3
rs.MoveFirst
rs.Fields("TenDangNhap")=btenDangNhap
rs.Fields("hoten")=bhoten
rs.Fields("matkhau")=bmatkhau
rs.Fields("diachi")=bdiachi
rs.Fields("dienthoai")=bdienthoai
rs.Fields("email")=bemail

rs.Update
rs.Close
set rs=nothing
Response.Write "Ban da sua doi thong tin
trong profile thanh cong"
%>

</BODY>
</HTML>

You might also like