The example of VBScript production notes

Source: Internet
Author: User
Tags chr contains error handling final goto variables tag name port number
Vbscript| notes

=========== three ways to add VBScript code ============
Suppose you already have a button named Btnsubmit, there are three ways to add VBScript code:
The first, most commonly used:
<script language= "VBScript" >
Private Sub Btnsubmit_onclick
MsgBox ("ok!")
End Sub
</script>

The second type uses the For/event property:
<script language= "VBScript" for= "btnsubmit" event= "OnClick" >
MsgBox ("ok!")
</script>

Third: You can not have to generate an event handler for an event individually, as long as the process of handling the event as a property in the element tag. Note that the value of the event's processing should be enclosed in single quotes, unlike other property values that are enclosed in double quotes.
<input type= "Submit" Name= "btnsubmit" value= "button" onclick= "MsgBox" ok! "' language= ' VBScript ' >

========on Error Resume Next Statement =========
If you do not use the On Error Resume Next statement, any run-time errors that occur will be fatal, that is, display an error message and terminate the operation.
On Error Resume Next causes the program to continue executing from the statement immediately following the statement that generated the error, or from the statement that immediately follows the last call procedure containing the On Error Resume Next statement. This statement can continue executing the program regardless of run-time errors, and you can then create an error-handling routine inside the procedure. Therefore, if you want to make internal error handling in a routine, you should execute the On Error Resume Next statement in each calling routine.

Error handling function in ==========vbscript ============
Strictly speaking, the error handling function in VBScript is relatively weak, when the error occurs, it does not have the means to call the error handler directly, it occurs when the error does not produce interrupt or prompt information mechanism. In Visual Basic, when an error occurs, you can use the On Error Goto ... Statement for error handling, and when the error occurs, the program automatically jumps to the code where the label indicated after Goto. This is not allowed in VBScript, however.
However, with the On Error Resume Next statement, it is possible to achieve some degree of error capture, except that all error traps must either be processed online or only the last error that occurs in the program can be reported. The following is a basic error-handling framework for VBScript.
Sub mysub ()
On Error Resume Next
........
' Online processing
If err.number=? Then
........
End If
' The report script encountered the last error message
If Err.number<>0 Then
MsgBox Err.Description
End If
End Sub
Note that after using the On Error Resume Next statement, except for the last error, the previous error has been cleared, so it is not possible to know all the errors that have occurred. In order to be able to deal with in time, it is recommended to use online processing method.

The Raise method of ============err object ==========
The Raise method of the Err object is used to raise a specific error.
You can use the following program to display the description of the error

On Error Resume Next
Err.Raise 6 ' generates an overflow error.
MsgBox ("Error #" & CStr (Err.Number) & "" & Err.Description)
Err.Clear ' clears the error.

========activex==========
ActiveX is a great way to make Web pages rich and colorful, although HTML controls provide basic visualization (such as buttons, etc.) but lack the visibility that users are already familiar with, and by adding some common (or developed) ActiveX controls, Users can get a sense of common computer applications. Use an ActiveX control with the <object> label. The ID property specifies the name of the control, followed by the ID number of the ActiveX control. If the control is not available on the browser's client computer, specify the source site location for the download of the control with codebase, such as Http://www.mysite.com/controls/mycontrol.ocx, and there is no need to provide any information other than to indicate that the control has a. ocx extension. The next step is to add the parameters with the <param> tag. A typical procedural paragraph is as follows:
<object id= "Objuseractivex" classid= "CLSID:7823A620-9DD9-11CF-A662-00AA00C066D2" >
<param name= "..." value= "...". >
<param name= "..." value= "...". >
</object>
If the developer does not want the viewer to know the parameters in its <param> tag, the content is encoded and then written to the <object> tag with the data property, such as:
<object id= "Objuseractivex" classid= "clsid:7823a620-9dd9-11cf-a662-00aa00c066d2" data= "...". >

==========filesystemobject Object =============

The FileSystemObject (FSO) object pattern allows you to work with folders and files on a wide range of properties, methods, and events using more familiar object.method syntax.
The FSO object pattern makes file processing easy. When working with files, the primary goal is to store the data in a valid space and resource in an accessible format. This requires the ability to create files, insert and change data, and output (read) data. Because storing data in a database, such as Access or a SQL server, adds a lot of overhead to your application, storing the data in a binary or text file can be the most effective solution. You may not want this overhead, or your data access requirements may not require all the extra functionality associated with a fully functional database.
The FSO object pattern is contained in the Scripting type library, which is located in the Scrrun.dll file. Therefore, to use the FSO object pattern, Scrrun.dll must be placed in the appropriate system directory of the WEB server.
In VBScript, use the following code to create an instance of FileSystemObject:

Dim FSO
Set fso = CreateObject ("Scripting.FileSystemObject")

Some of the features in the FileSystemObject object pattern are superfluous. For example, you can use the CopyFile method of a FileSystemObject object, or you can copy a file by using the Copy method of the file object. The two methods are the same, and the two methods make programming more flexible.

To access an existing file, use the GetFile in the FileSystemObject object
Method:

Dim FSO, F1
Set fso = CreateObject ("Scripting.FileSystemObject")
Set f1 = fso. GetFile ("C:\test.txt")

Once you have a handle to the object, you can access its properties. To find out when the file was last modified, use the following VBScript syntax:

Response.Write "File Last Modified:" & F1. DateLastModified

The way to create an empty text file is by using the CreateTextFile method. The following example demonstrates how to create a text file in VBScript in this way:

Dim FSO, F1
Set fso = CreateObject ("Scripting.FileSystemObject")
Set f1 = fso. CreateTextFile ("C:\testfile.txt", True)

To open an existing file, use the OpenTextFile method of the FileSystemObject object.
To write data to an open text file, use the Write, WriteLine, or WriteBlankLines method of the TextStream object according to the tasks described in the following table.
The following VBScript example demonstrates how to open a file, add data to a file, and then close the file:
Sub CreateFile ()
Dim FSO, TF
Set fso = CreateObject ("Scripting.FileSystemObject")
Set tf = fso. CreateTextFile ("C:\testfile.txt", True)
' Writes a line with a new line character.
Tf. WriteLine ("Testing 1, 2, 3.")
' Write three new line characters to the file.
Tf. WriteBlankLines (3)
' Write a line.
Tf. Write ("This is a test.")
Tf. Close
End Sub

To read data from a text file, use the read, ReadLine, or ReadAll methods. The following table describes which methods should be used for different tasks.
If you use the Read or ReadLine method and you want to skip a particular part of the data, use the Skip or SkipLine method. The result text of the Read method exists in a string that can be displayed in a control, or it can be parsed, connected, and so on by string functions such as left, right, and Mid.
The following VBScript example demonstrates how to open a file and how to write data to a file and read data from a file:

Sub Readfiles
Dim FSO, F1, TS, s
Const ForReading = 1
Set fso = CreateObject ("Scripting.FileSystemObject")
Set f1 = fso. CreateTextFile ("C:\testfile.txt", True)
' Write a line.
Response.Write "Writing File <br>"
F1. WriteLine "Hello World"
F1. WriteBlankLines (1)
F1. Close
' Read the contents of the file.
Response.Write "Reading File <br>"
Set ts = fso. OpenTextFile ("C:\testfile.txt", ForReading)
s = ts. ReadLine
Response.Write "File contents = '" & S & "'"
Ts. Close
End Sub

============== "Cookie" Technology =============

The term "Cookie" represents a string assigned to a client application. The word "cookie" comes from the "Magic Cookie" UNIX programming concept and is sometimes called "notation" (token). Generally speaking, using the term "notation" is easier to understand than the word "Cookie".
A cookie is a string that typically contains the values of many group variable names and variables, separated by semicolons between names and values, and a semicolon followed by a space, separated by an equal sign between variable names and variable values, a typical cookie string as follows:
value1=100; Value2=good; Sale50
Returns the current cookie string with the Document object's Cookie property.
Use document. Cookie= "value1=100" is a way to assign a value to a cookie, and if it has this variable, it will be replaced with a new value, and a variable will be created for it if it is not in the cookie.

The cookie technology above stores variables and variable values in memory, not on the hard disk. All pages share a cookie space, and if page A and page B are written separately in the cookie, the cookie data for each page can be displayed on any page using Document.cookie. As long as there is an IE window open will not lose cookies, once all IE windows are closed, then all cookies are cleared.

Here is the function I wrote myself to read the cookie variable.

<script language= "VBScript" >
function Readcookie (Pcook)
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''''''''''''''''
' This function is used to read the data in the cookie.
' Process: First delete the Pcook variable in the cookie before the string, and then delete the Pcook variable after the string, is the Pcook value.
' Enter: The name of the variable to read.
' Output: The value of the variable name. If you do not have the value of the variable, assign an initial number to it.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''''''''''''''''
Dim Whereis_pcook ' The starting position of the Pcook tag name to find in the cookie
Dim Howlong_pcook ' Length of the pcook tag name to find
Dim Howlong_cookie ' Length of entire cookie
Dim Whereis_fenhao ' Find Semicolon in endstring (starting position of;)
Dim endstring ' holds a temporary string that is processed and finally gets pcook value

Whereis_pcook = Instr (Document.cookie,pcook)
If Whereis_pcook = 0 Then
' If the Pcook value is not present in the current cookie, it will be initialized
Select Case Pcook
Case "Value1"
Document. Cookie= "Value1=100"
endstring= "100"
Case "value2"
Document. Cookie= "Value2=good"
Endstring= "Good"
Case "Value3"
Document. Cookie= "Value3=sale50"
Endstring= "Sale50"
End Select
Else
Howlong_pcook = Len (pcook)
Howlong_cookie=len (Document.cookie)
' Start with the Pcook value from the cookie to the end of the cookie string.
' Note that the cookie is separated by semicolons and followed by a space after the semicolon, so there is a "+1" in the following statement
In addition, the variable names and variables are separated by an equal sign, so the following statement has "-1"
' Of course, the above two offsets each other, but in order to better understand this statement, it still retains
Endstring = Right (Document.cookie,howlong_cookie-whereis_pcook + 1-howlong_pcook-1)
Whereis_fenhao=instr (endstring, ";")
' If the semicolon is not found, this variable is the last one, so endstring is the final result;
' If you find a semicolon, take the string before the semicolon and get the final result.
If Whereis_fenhao <> 0 Then
Endstring=left (endstring,whereis_fenhao-1)
End If
End If
Readcookie=endstring
End Function
</script>

========== Calendar Control ============
Operating system: Windows2000 Professional
Under FrontPage2000 named "Calendar Control 9.0", classid= "CLSID:8E27C92B-1264-101C-8A2F-040224009C02"
You can use Calendar.year,calendar.month,calendar.day to invoke the value of the control's month and year, and the day calendar changes the date of year to trigger Calendar_newyear (), Calendar_newmonth (), Calendar_newday () event.
Note that when you select a year or month in the Drop-down list, the Calendar.year,calendar.month,calendar.day three values are zeroed.

========= on the color constants of VB ============
The color constants that use the VBS in VBScript can have unexpected colors, such as Document.bgcolor=vbyellow
Does not display the page background as yellow, but rather light blue.
The reason is that the color constants of the VBS differ from the representation of the colors in the HTML, and the color constants of the VBS vbyellow are "HFFFF", and the VBS is meant to represent a color with a value of "ffff00", but because the value of the constant is not written as a 6-digit hexadecimal number, So HTML interprets it as "00ffff", causing an error.
The colors that are actually displayed on the page for the VBS color constants can be tested in FrontPage. In the page properties select the background color/other color, in the value of the VBS directly fill in the color constants of the machine value, determined after the system will be converted to get the actual display in the page color.
Some of the color constants of the VBS have an internal value of 6 digits that are symmetric, so they are displayed correctly, such as Vbgreen (hFF00) and Vbmagenta (HFF00FF).

=================== Elements Object ===================
Private Sub Window_onload ()
For i = 0 to 6
Frmres.elements (i). value= ""
Next
End Sub
This window initializer clears the value of the first 7 elements (No. 0-6th elements) of the Frmres form in the page, noting that the loop condition cannot be written as
For I=1 to 7
Since this system will be considered to be the 1th-7th element, the system's identification of the element is starting from 0.

====================== Set Statement =======================
Dim theform
Set theform = Document.frmres
The above statement sets the Theform variable to refer to the Frmres form, which reduces the writing and makes the changes to the page more adaptable. In a program, you can reference frmres elements in this way:
TheForm.txtName.focus

NOTE: The SET statement assigns an object reference to a variable or property, and the statement that sets the theform variable must be preceded by a set, or there will be an error.
When you use set to assign an object reference to a variable, you do not create a copy of the object for the variable, but instead create a reference to the object. You can have multiple object variables referencing the same object. Because these variables are object references (not replicas), any changes made to the object affect all variables that reference the object.

===========location Object ===========
Each window has a location object that defines the page address information for the home page it contains. The main properties of the Location object are:
URL of the HREF Web page
Protocal Network protocol
Host,hostname Host Name
Pathname Path
Port Port number
You can also use the Location.href=newurl statement to redirect page addresses.

==========window Object ================
The properties and methods of the Window object do not need to indicate the name of the windows, so the method name of the window object can be viewed as a system statement. If the name of the window can be window.name, you can also use name directly.

The Status property is a State bar prompt that changes the status bar information using the following statement:
status= "I am busy! Please wait for a miniter! "

The Navigate method of the Window object can redirect the page address. such as navigate "http://www.sina.com.cn"

============== Alert and Confirm statements =================
Alert "Bill is seriously carrying out a biological experiment."
The alert method of the Window object is used to display the hint text, as shown above. The Confirm method of the Window object pops up a dialog box with the OK and Cancel buttons, which you can use to handle the user's selections. As pictured above.
Flag=prompt ("is Bill doing a biological experiment?") ")
If Flag then
MsgBox "Is in progress ..."
Else
MsgBox "To play ..."
End If

Comparison of prompt method of ========== window object with InputBox function ==========
The format of the prompt method for the Window object is:
Username=prompt ("Please enter your name:", "Jack")
The first parameter is the hint, and the second parameter is the default value. As pictured above. The InputBox function can display a more personalized Input dialog box, in the form of:
Username=inputbox ("Please enter your name:", "Enter the dialog box", "Jack")
The first argument is the message, the second argument is the dialog box title, and the third parameter is the default value. As pictured above.
The prompt method is essentially the same as the InputBox function, with the words "JavaScript" in the dialog box that pops up prompt method, and the words "VBScript" in the dialog that pops up InputBox function.

=========history Object ============
The History object contains a list of the home pages that are displayed in the window.
The forward method is to page forward, equivalent to the "forward" button in IE. The back method is to page backwards, equivalent to the "back" button in IE. Both the forward and back methods can take parameters, indicating the number of pages forward and backwards.
The Go method is going to a page whose parameters are relative to the current page, a positive number is forward, and a negative number is back.
The Length property is the total number of Windows displayed by the window.

such as History.back
History.go 3


=======link Object =======
You can access the link property with the Document object, which is an array that counts from 0 and contains all the linked objects in which the order of the linked objects is determined by the definition of the linked object in the HTML file. The properties of a linked object are similar to the properties of the Location object of the window.

The following program changes the href attribute of the first link in the page. The advantage of assigning the name of a linked object to an LNK variable with a SET statement is that, in some cases, the name of each object cannot be written out (if you cannot name it with the Name property), and you can refer to the object with the SET statement.

Set Lnk=document.links (0)
lnk.href= "Page-1.htm"
MsgBox "Link changed to" & Lnk.href

The length property of the link object is the number of all linked objects in the home page. The following program will display all the links in the Web page.

Dim msg, I, LNK
For I=0 to Document.links.length-1
Set Lnk=document.links (i)
Msg=msg & i+1 & "---" & lnk.href & VbCrlf
Next
MsgBox msg

=========frame Object ====================
A Frame object is contained in a Window object, but is actually equivalent to a Window object that can use various properties, methods, and events of a Window object, or it can contain objects that any window can contain, including other frame objects nested within a Frame object.
A typical frame nested HTML source file, divides a window into the upper and lower parts, then divides the upper part into two parts, and then divides the upper left into the upper and lower parts:

<frameset cols= "*,505" >
<frameset rows= "80,*" >
<frame name= "Topframe" src= "document.write-top.htm" >
<frame name= "MainFrame" src= "document.write-main.htm" >
</frameset>
<frame name= "Rightframe" src= "document.write-right.htm" >
</frameset >


Access the other frame from the current frame, in the form of the following:
Parent. FrameName.document.write "CCCCCCCC"
Regardless of how many layers the frame is nested, you need only one parent, rather than a directory-level designation.

============ restricted text boxes can only enter numbers ===========
The following program handles the onkeyup event for the text box and deletes the last character you typed if it is not a number.
Issues not resolved by the program:
1. If you press the non-numeric key, you will type a string of text, and only the last character will be deleted.
2. If you do not type a non-numeric key in the final position, it will not be corrected.

Sub Txta_onkeyup
Dim a
A=right (txta.value,1)
If a < Chr (a) or a > Chr (a) Then
Txta.value=left (Txta.value,len (Txta.value)-1)
End If
End Sub

Relationship of ================== window objects =================
=================== other ===================
-If the type of scripting language is not specified in HTML, the browser default scripting language is JavaScript.
-If the button in the form <form> is set to the submit type, no matter what the statement in the onclick program is, it always jumps to the <action> page defined in <form>, so The button for the submit type is not appropriate to check that the form is filled out correctly, because even checking for errors will jump to the next form and the check will lose its meaning. You can move it outside of <form> as a stand-alone button, or set its type to <button>.
-You can use MsgBox to display a message box to play the role of "breakpoint".
The-focus method causes the focus to move to the current element. such as TheForm.txtPhone.focus
The-select method causes all text in the corresponding text box to be selected. such as TheForm.txtPhone.select
-The content between <body> and </body> in the page is represented as: Document.body.innerHTML

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.