次の方法で共有


Creating Simple ASP Pages

An Active Server Pages (ASP) file is a text file with the extension .asp that contains any combination of the following: text, HTML tags, and server-side scripts in an COM-compliant scripting language such as Microsoft VBScript?.

A quick way to create an .asp file is to rename your HTML files by replacing the existing .htm or .html file name extension with an .asp extension. If your file does not contain any ASP functionality, then the server dispenses with the ASP script processing and efficiently sends the file to the client. As a Web developer, this affords you tremendous flexibility because you can assign your files .asp extensions, even if you do not plan on adding ASP functionality until later.

To publish an .asp file on the Web, save the new file in a virtual directory on your Web site (be sure that the directory has Script or Execute permission enabled). Next, request the file with your browser by typing in the file's URL. (Remember, ASP pages must be served, so you cannot request an .asp file by typing in its physical path.) After the file loads in your browser, you will notice that the server has returned an HTML page. This may seem strange at first, but remember that the server parses and executes all ASP server-side scripts prior to sending the file. The user will always receive standard HTML.

You can use any text editor to create .asp files. As you progress, you may find it more productive to use an editor with enhanced support for ASP, such as Visual InterDev. (For more information, visit the Microsoft Visual InterDev Web site.)

Adding Server-Side Script Commands

A server-side script is a series of instructions used to sequentially issue commands to the Web server. (If you have developed Web sites previously, then you are probably familiar with client-side scripts, which run on the Web browser.) In .asp files, scripts are differentiated from text and HTML by delimiters. A delimiter is a character or sequence of characters that marks the beginning or end of a unit. In the case of HTML, these delimiters are the less than (<) and greater than (>) symbols, which enclose HTML tags.

ASP uses the delimiters <% and %> to enclose script commands. Within the delimiters, you can include any command that is valid for the scripting language you are using. The following example shows a simple HTML page that contains a script command:

<HTML> 
  <BODY> 
  This page was last refreshed on <%= Now() %>. 
  </BODY> 
</HTML> 

The VBScript function Now() returns the current date and time. When the Web server processes this page, it replaces <% = Now() %> with the current date and time and returns the page to the browser with the following result:

This page was last refreshed on 01/29/99 2:20:00 PM.

Commands enclosed by delimiters are called primary script commands, which are processed using the primary scripting language. Any command that you use within script delimiters must be valid for the primary scripting language. By default, the primary scripting language is VBScript, but you can also set a different default language. See Working with Scripting Languages.

If you are already familiar with client-side scripting, you are aware that the HTML <SCRIPT> tag is used to enclose script commands and expressions. You can also use the <SCRIPT> tag for server-side scripting, whenever you need to define procedures in multiple languages within an .asp file. For more information, see Working with Scripting Languages.

Mixing HTML and Script Commands

You can include, within ASP delimiters, any statement, expression, procedure, or operator that is valid for your primary scripting language. A statement, in VBScript and other scripting languages, is a syntactically complete unit that expresses one kind of action, declaration, or definition. The conditional If...Then...Else statement that appears below is a common VBScript statement:

<%  
  Dim dtmHour 

  dtmHour = Hour(Now()) 

  If dtmHour < 12 Then 
    strGreeting = "Good Morning!" 
  Else   
    strGreeting = "Hello!" 
  End If    
%>  

<%= strGreeting %> 

Depending on the hour, this script assigns either the value "Good Morning!" or the value "Hello!" to the string variable strGreeting. The <%= strGreeting %> statement sends the current value of the variable to the browser.

Thus, a user viewing this script before 12:00 noon (in the Web server's time zone) would see this line of text:

Good Morning!

A user viewing the script at or after 12:00 noon would see this line of text:

Hello!

You can include HTML text between the sections of a statement. For example, the following script, which mixes HTML within an If...Then...Else statement, produces the same result as the script in the previous example:

<% 
  Dim dtmHour 

  dtmHour = Hour(Now()) 

  If dtmHour < 12 Then 
%>  
  Good Morning! 
<% Else %> 
  Hello! 
<% End If %> 

If the condition is true-that is, if the time is before noon-then the Web server sends the HTML that follows the condition ("Good Morning") to the browser; otherwise, it sends the HTML that follows Else ("Hello!") to the browser. This way of mixing HTML and script commands is convenient for wrapping the If...Then...Else statement around several lines of HTML text. The previous example is more useful if you want to display a greeting in several places on your Web page. You can set the value of the variable once and then display it repeatedly.

Rather than interspersing HTML text with script commands, you can return HTML text to the browser from within a script command. To return text to the browser, use the ASP built-in object Response. The following example produces the same result as the previous scripts:

<%  
  Dim dtmHour 

  dtmHour = Hour(Now()) 

  If dtmHour < 12 Then 
    Response.Write "Good Morning!" 
  Else   
    Response.Write "Hello!" 
  End If    
%>  

Response.Write sends the text that follows it to the browser. Use Response.Write from within a statement when you want to dynamically construct the text returned to the browser. For example, you might want to build a string that contains the values of several variables. You will learn more about the Response object, and objects in general, in Using Components and Objects and Sending Content to the Browser. For now, simply note that you have several ways to insert script commands into an HTML page.

You can include procedures written in your default primary scripting language within ASP delimiters. Refer to Working with Scripting Languages for more information.

If you are working with JScript commands, you can insert the curly braces, which indicate a block of statements, directly into your ASP commands, even if they are interspersed with HTML tags and text. For example:

<%  
  if (screenresolution == "low") 
  { 
%> 
This is the text version of a page. 
<% 
  } 
  else 
  { 
%> 
This is the multimedia version of a page. 
<% 
  }  
%> 

--Or--

<%  
  if (screenresolution == "low") 
  {  
    Response.Write("This is the text version of a page.") 
  } 
  else 
  {  
    Response.Write("This is the multimedia version of a page.") 
  }  
%> 

Using ASP Directives

ASP provides directives that are not part of the scripting language you use: the output directive and the processing directive.

The ASP output directive<%= expression %> displays the value of an expression. This output directive is equivalent to using Response.Write to display information. For example, the output expression <%= city %> displays the word Baltimore (the current value of the variable) on the browser.

The ASP processing directive<%@ keyword %> gives ASP the information it needs to process an .asp file. For example, the following directive sets VBScript as the primary scripting language for the page:

<%@ Language= "VBScript" %>

The processing directive must appear on the first line of an .asp file. To add more than one directive to a page, the directive must be within the same delimiter. Do not put the processing directive in a file included with the #include statement. (For more information, see Including Files.) You must use a space between the at sign (@) and the keyword. The processing directive has the following keywords:

ms524741.alert_caution(en-us,VS.90).gifImportant Note:

You can include more than one keyword in a single directive. Keyword/value pairs must be separated by a space. Do not put spaces around the equal sign (=).

The following example sets both the scripting language and the code page:

<%@ LANGUAGE="JScript" CODEPAGE="932" %>

White Space in Scripts

If your primary scripting language is either VBScript or JScript, ASP removes white space from commands. For all other scripting languages, ASP preserves white space so that languages dependent upon position or indentation are correctly interpreted. White space includes spaces, tabs, returns, and line feeds.

For VBScript and JScript, you can use white space after the opening delimiter and before the closing delimiter to make commands easier to read. All of the following statements are valid:

<% Color = "Green" %> 

<%Color="Green"%> 

<% 
Color = "Green" 
%> 

ASP removes white space between the closing delimiter of a statement and the opening delimiter of the following statement. However, it is good practice to use spaces to improve readability. If you need to preserve the white space between two statements, such as when you are displaying the values of variables in a sentence, use an HTML nonbreaking space character (?). For example:

<% 
  'Define two variables with string values. 
  strFirstName = "Jeff" 
  strLastName = "Smith" 
%> 

<P>This Web page is customized for "<%= strFirstName %> <%= strLastName %>." </P> 

The best way to learn about ASP is to look at examples; alter integer values, strings, and statements you are curious about; and determine what changes occur in the browser.

In this lesson you perform the following tasks:

  • Example 1: Create, save, and run an ASP page using HTML and VBScript.

  • Examples 2, 3, and 4: Add functionality and logic to your ASP page by using built-in functions and conditional script statements.

VBScript is the default scripting language for ASP pages; however, the delimiters are the same for JScript. Use angle brackets as delimiters around HTML tags just as you would in any .htm page, as follows:

< 
example></ 
example> 

Use percent signs with brackets as delimiters around script code, as follows:

<%  
example %> 

You can put many script statements inside one pair of script delimiters, as in the following example:

<font face="MS Gothic"> 
<% 
'Create a variable. 
dim strGreeting 

'Set the greeting. 
strGreeting = "Hello  World!" 

'Print out the greeting, using the ASP Response object. 
Response.Write strGreeting & "<BR>" 

'Also print out the greeting using the <%= method. 
%> 
<%=strGreeting%> 
</font> 

This code displays the following text in the browser:

 Hello World! 
 Hello World! 

Here is the previous example using JScript:

<%@ Language= "JScript" %> 

<font face="MS Gothic"> 
<% 
//Create a variable. 
var strGreeting; 

//Set the greeting. 
strGreeting = "Hello World!"; 

//Print out the greeting, using the ASP Response object. 
Response.Write(strGreeting + "<BR>"); 

//Also print out the greeting using the <%= method. 
%> 
<%=strGreeting%> 
</font> 

To create ASP pages, use a text editor such as Notepad and save the page with the .asp extension instead of .htm. The .asp filename extension tells IIS to send the page through the ASP engine before sending the page to a client. ( Note: In the Notepad Save As dialog box, when Text Documents (*.txt) is selected in the Save as type box, Notepad automatically appends .txt to the filename. To prevent this, select All Files in the Save as type box, type the full filename MyFile.asp in the File Name field, and then click Save.)

Example 1

This example displays a greeting, the date, and the current time. To run this example, copy and paste the following code into an empty file and save it in the x:\Inetpub\Wwwroot\Tutorial directory as Example1.asp. View the example with your browser by typing https://localhost/Tutorial/Example1.asp in the address bar.

<%@ Language= "VBScript" %> 

  <html> 
  <head> 
  <title>Example 1</title> 
  </head> 
  <body> 
  <font face="MS Gothic"> 

  <H1>Welcome to my Home Page</H1> 
  <% 
   'Create some variables. 
   dim strDynamicDate 
   dim strDynamicTime 

   'Get the date and time. 
   strDynamicDate = Date() 
   strDynamicTime = Time() 

   'Print out a greeting, depending on the time, by comparing the last 2 characters in strDymamicTime to "PM". 
   If "PM" = Right(strDynamicTime, 2) Then 
      Response.Write "<H3>Good Afternoon!</H3>" 
   Else 
      Response.Write "<H3>Good Morning!</H3>" 
   End If 
  %> 
  Today's date is <%=strDynamicDate%> and the time is <%=strDynamicTime%>  

  </font> 
  </body> 
  </html> 

In the browser, you should see something like the following (depending on the date and time you perform this exercise):

Welcome to my Home Page

Good Afternoon!

Today's date is 10/20/2000 and the time is 7:29:50 PM

The Web server processes Example1.asp in the following sequence

  1. <%@ Language= "VBScript" %> tells the ASP engine to use the VBScript engine to translate the script code.

  2. The ASP engine ignores the HTML code blocks.

  3. The ASP engine executes the code in the <%...%> blocks and replaces the blocks with placeholders. The results of the Response.Write strings and <%=...%> strings are saved in memory on the server.

  4. The results of the Response.Write strings and <%=...%> strings are injected into the HTML code at the matching placeholders before the page leaves the ASP engine.

  5. The complete page leaves the ASP engine as a file of HTML code, and the server sends the page to the client.

Example 2

This example incorporates a For...Next loop in the ASP page to add a little dynamic logic. The For...Next loop is one of six conditional statements available to you. The others are Do...Loop, For Each...Next, If...Then...Else...End If, Select..Case...End Select, and While...Wend. These statements are documented at Windows Script Technologies under VBScript.

Copy and paste the following code in your text editor, and save the file as Example2.asp. View the example with your browser by typing https://localhost/Tutorial/Example2.asp in the address bar.

The processing order is the same as in Example1.asp.

<%@ Language= "VBScript" %>  
<html> 
<head> 
<title>Example 2</title> 
</head> 
<body> 
<font face="MS Gothic"> 

<% 
 'Create a variable. 
 dim strTemp 
 dim font1, font2, font3, font, size 

 'Set the variable. 
 strTemp= "BUY MY PRODUCT!" 
 fontsize = 0 

 'Print out the string 5 times using the For...Next loop. 
 For i = 1 to 5 

   'Close the script delimiters to allow the use of HTML code and <%=... 
   %> 
   <table align=center><font size= <%=fontsize%>> <%=strTemp%> </font></table> 
   <% 
   fontsize = fontsize + i 

 Next 

%> 
<table align=center><font size=6><B> IT ROCKS! <B></font></table>
<BR> 

</font> 
</body> 
</html>  

In the browser, you should see the

"BUY MY PRODUCT!"

string displayed five times in increading sizes.

Here is Example 2 using JScript:

<%@ Language= "JScript" %>
  <html> 
  <head> 
  <title>Example 2</title> 
  </head> 
  <body> 
  <font face="MS Gothic"> 

  <% 
  //Create?a variable. 
  var strTemp; 
  var font1, font2, font3, font, size; 

  //Set the variable. 
  strTemp= "BUY MY PRODUCT!"; 
  fontsize = 0; 

  //Print out the string 5 times using the For...Next loop. 
  for (i = 1; i < 6; i++) { 

  //Close the script delimiters to allow the use of HTML code and <%=... 
  %>. 
  <table align=center><font size= <%=fontsize%>> <%=strTemp%> </font></table> 
  <% 
  fontsize = fontsize + i; 

  } 

  %> 
  <table align=center><font size=6><b> IT ROCKS! <b></font></table>

Example 3

There are more multilingual Web sites every day, as businesses see the need to offer their products around the world. Formatting your date, time, and currency to match the user's locale is good for diplomacy.

In Example 3, a predefined function displays the date and currency on your ASP page. The date and currency are formatted for different locales using the GetLocale function, the SetLocale function, the FormatCurrency function, and the FormatDateTime function. Locale identification strings are listed in the Locale ID Chart on MSDN. (This example doesn't cover changing the CodePage to display non-European characters on European operating systems. Please read CodePage topics in your IIS Help for more information.)

There are more than 90 predefined functions in VBScript. They are all well-defined at Windows Script Technologies under VBScript , Documentation , Language Reference , Functions.

Copy and paste the following code in your text editor, and save the file as Example3.asp in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your browser by typing https://localhost/Tutorial/Example3.asp in the address bar.

<%@ Language= "VBScript" %> 

<html> 
  <head> 
  <title>Example 3</title> 
  </head> 
  <body> 
  <font face="MS Gothic"> 

  <H3>Thank you for your purchase.  Please print this page for your records.</H3> 
  <% 
   'Create some variable. 
   dim saveLocale 
   dim totalBill 

   'Set the variables. 
   saveLocale = GetLocale 
   totalBill = CCur(85.50) 

   'For each of the Locales, format the date and the currency 
   SetLocale("fr") 
   Response.Write"<B>Formatted for French:</B><BR>" 
   Response.Write FormatDateTime(Date, 1) & "<BR>" 
   Response.Write FormatCurrency(totalBill) & "<BR>" 
   SetLocale("de") 
   Response.Write"<B>Formatted for German:</B><BR>" 
   Response.Write FormatDateTime(Date, 1) & "<BR>" 
   Response.Write FormatCurrency(totalBill) & "<BR>" 
   SetLocale("en-au") 
   Response.Write"<B>Formatted for English - Australia:</B><BR>" 
   Response.Write FormatDateTime(Date, 1)& "<BR>" 
   Response.Write FormatCurrency(totalBill) & "<BR>" 

   'Restore the original Locale 
   SetLocale(saveLocale) 
  %> 

  </font> 
  </body> 
  </html> 

In the browser, you should see the following:

Thank you for your purchase. Please print this page for your records.

Formatted for French:

vendredi 20 octobre 2000

85,50 F

Formatted for German:

Freitag, 20. Oktober 2000

85,50 DM

Formatted for English - Australia:

Friday, 20 October 2000

$85.50

Example 4

The most common functions used in ASP Scripts are those that manipulate strings. The most powerful string functions use regular expressions. Because regular expressions are difficult to adapt to, Example 4 shows you how to replace characters in a string by using a string expression and a regular expression. Regular expressions are defined at Windows Script Technologies under VBScript , Documentation , Regular Expressions Guide.

Copy and paste the following code in your text editor, and save the file as Example4.asp in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your browser by typing https://localhost/Tutorial/Example4.asp in the address bar.

<%@ Language= "VBScript" %> 

  <html> 
  <head> 
  <title>Example 4</title> 
  </head> 
  <body> 
  <font face="MS Gothic"> 

  <H3>Changing a Customer's Street Address</H3> 
  <% 
   'Create some variables. 
   dim strString 
   dim strSearchFor     ' as a string 
   dim reSearchFor     ' as a regular expression 
   dim strReplaceWith 

   'Set the variables. 
   strString = "Jane Doe<BR>100 Orange Road<BR>Orangeville, WA<BR>98100<BR>800.555.1212<BR>" 
   '   Using a string object 
   strSearchFor = "100 Orange Road<BR>Orangeville, WA<BR>98100" 
   '   Using a regular expression object 
   Set reSearchFor = New RegExp 
   reSearchFor.Pattern = "100 Orange Road<BR>Orangeville, WA<BR>98100" 
   reSearchFor.IgnoreCase = False 

   strReplaceWith = "200 Bluebell Court<BR>Blueville, WA<BR>98200" 

   'Verify that strSearchFor exists... 
   '   using a string object. 
   If Instr(strString, strSearchFor) Then 
     Response.Write "strSearchFor was found in strString<BR>" 
   Else 
     Response.Write "Fail" 
   End If 
   '   using a regular expression object. 
   If reSearchFor.Test(strString) Then 
     Response.Write "reSearchFor.Pattern was found in strString<BR>" 
   Else 
     Response.Write "Fail" 
   End If 

   'Replace the string... 
   Response.Write "<BR>Original String:<BR>" & strString & "<BR>" 
   '   using a string object. 
   Response.Write "String where strSearchFor is replaced:<BR>" 
   Response.Write Replace(strString, strSearchFor, strReplaceWith) & "<BR>" 
   '   using a regular expression object. 
   Response.Write "String where reSearchFor is replaced:<BR>" 
   Response.Write reSearchFor.Replace(strString, strReplaceWith) & "<BR>" 
  %> 

  </font> 
  </body> 
  </html> 

In the browser, you should see the following:

Changing a Customer's Street Address

strSearchFor was found in strString

reSearchFor.Pattern was found in strString

Original String:

Jane Doe

100 Orange Road

Orangeville, WA

98100

800.555.1212

String where strSearchFor is replaced:

Jane Doe

200 Bluebell Court

Blueville, WA

98200

800.555.1212

String where reSearchFor is replaced:

Jane Doe

200 Bluebell Court

Blueville, WA

98200 800.555.1212