Chinaunix首页 | 论坛 | 认证专区 | 博客 登录 | 注册
  • 博客访问: 5547946
  • 博文数量: 915
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 5216
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-15 17:17
文章分类

全部博文(915)

文章存档

2011年(1)

2008年(134)

2007年(287)

2006年(493)

我的朋友
微信关注

IT168企业级官微



微信号:IT168qiye



系统架构师大会



微信号:SACC2013

订阅
热词专题
ASP JavaScript Lessons(8-14) 2006-12-31 14:48:22

分类: Java

-------------------------------- 8 -----------------------------------

The Request Object

Request Object:

Request has five (5) Collections, one (1) Property, and one (1) Method. You'll use the Collections far more than the property or the method.

Request Collections:

Below is a table of the Request Collections and descriptions of how they are used.

Request Collections
ClientCertificateRequest.ClientCertificate("Key[Field]")
Client security info for SSL encryption
CookiesRequest.Cookies("cookieName")
Holds cookie value stored on the client
FormRequest.Form("formName")
Holds value sent via HTML Form
QueryStringRequest.QueryString("keyName")
Name/Value pair appended to the end of the URL
ServerVariablesRequest.ServerVariables("variableName")
Hold values sent in the HTTP Headers

ClientCertificate:

Request.ClientCertificate is used with S.S.L. (Secure Sockets Layer). It is beyond the scope of this web site.

Cookies:

We will learn Request.Cookies and Response.Cookies together in Lesson 08. Please be patient.

Form:

Request.Form is probably the workhorse of the Request Collections. The first script is a repeat from Lesson 03.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

Type something into the text box and submit it.



How Much Money do you make each month?






Click Here to run script08.asp in a new window. It posts information to script08a.asp which is found below. In turn, script08a.asp posts information to script08b.asp which is also found below.

<%@LANGUAGE="JavaScript"%>
<%
var WebPageVariable = new String( Request.Form("WebPageVariable") )
WebPageVariable = WebPageVariable.toUpperCase();

var monthlySalary = new String( Request.Form("monthlySalary") )
monthlySalary = monthlySalary.toLowerCase();
%>

The Web Page Variable you typed is: <%=WebPageVariable%>

The monthly salary you listed is: <%=monthlySalary%>



Click the button to see Query Strings




We'll be using Request.Form when we "Post" an HTML form to the server. Notice that the NAME attribute in the HTML form corresponds to the "name" in Request.Form("name"). To be more specific, corresponds with Request.Form("WebPageVariable"). We already talked about the need for the new String( ) constructor back in Lesson 03.

QueryString:

We'll be using Request.QueryString when we use an HTML form to "Get" a page from the server. Request.QueryString() is very similar to Request.Form(). Take a look at script08b.asp which I printed below.

<%@LANGUAGE="JavaScript"%>
<%
var QueryVariable = new String( Request.QueryString("QueryVariable") )
%>

The QueryString Value is: <%=QueryVariable%>

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>
Click Here
for the link to script08b.asp?QueryVariable=<%=QueryVariable%>
<%
} //closing bracket for if statement.
%>

If you haven't already, Click Here to run script08.asp in a new window. Cycle through all the forms and links, and then come back.

You can use Request.QueryString in two different ways. You can either use an HTML form to "Get" a page from the server, which will generate a query string. Or you can manually build a query string and add it to the backside of a link. We'll dissect script08b.asp from top to bottom.

var QueryVariable = new String( Request.QueryString("QueryVariable") )

The line above in script08b.asp corresponds to the line below from script08a.asp


The NAME="someName" in the HTML form becomes the Request.QueryString("someName") on the next page.

About half way into script08b.asp are the lines I reprinted below.

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>

We've already converted Request.QueryString() into a JavaScript string at the top of the script. So, now we can do a string comparison.

If the QueryVariable hasn't already been set equal to "Lesson 08's new Query!" then we do that. Then we use the escape( ) method to convert white space and special characters into Unicode. (URL's should contain neither whitespace, nor most special characters.)

In lesson 14 we'll see a better way to encode URL's. When we study the Server Object, we'll see Server.URLEncode(). But for now, just know that escape() works.

You can have more than one QueryString on each page. If you lose count of your QueryStrings, then you use Request.QueryString.Count to tell you the number.

The Request Shortcut:

Request.Form() and Request.QueryString() share a shortcut. Request.Form("WebPageVariable") can be abbreviated as Request("WebPageVariable") and Request.QueryString("QueryVariable") can be abbreviated as Request("QueryVariable").

ServerVariables:

Server Variables represent the HTTP Headers sent to the server by the client. I won't demonstrate them all, because there are too many.

<%@LANGUAGE="JavaScript"%>










ALL_RAW<%=Request.ServerVariables("ALL_RAW")%>
REMOTE_ADDR<%=Request.ServerVariables("REMOTE_ADDR")%>
HTTP_USER_AGENT<%=Request.ServerVariables("HTTP_USER_AGENT")%>
URL<%=Request.ServerVariables("URL")%>


Click Here to run the script in a new window.

Demonstrated above are four (4) server variables. There are (give or take) about 50 server variables available. You can look up the full list of server variables for yourself on the internet.

Misc. Notes:

Request.BinaryRead() is the lone method and TotalBytes is the lone property. Request.BinaryRead(Request.TotalBytes) retrieves data from an HTML form using "POST." You must supply the TotalBytes as an argument. It stores the data into an array. BinaryRead cannot be used at the same time as Request.Form().

Next Stop, Cookies:

The only Request Collection I did not cover was Cookies. I want to cover Request.Cookies and Response.Cookies side by side. So we'll do that in Lesson 09.


-------------------------------- 9 -----------------------------------

ookies and Cookies

Response Cookies in General:

We'll start with the Response Cookies collection. I don't think it could be any easier. You simply put the name of the cookie in the argument. The corresponding value is a string. The only time it gets complicated is when you use keys (which I demonstrate below).

<%@LANGUAGE="JavaScript"%>
<%
var Tomorrow=new Date()
Tomorrow.setDate(Tomorrow.getDate() + 1)
myExpire = (Tomorrow.getMonth() + 1) + "/" + Tomorrow.getDate()
myExpire += "/" + Tomorrow.getFullYear()

Response.Cookies("firstCookie") = "I like cookies."
Response.Cookies("firstCookie").Expires=myExpire

Response.Cookies("secondCookie") = "ASP Cookies Are Easy."
Response.Cookies("secondCookie").Expires=myExpire

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."
Response.Cookies("thirdCookie").Expires=myExpire
%>


We're just setting <%=Response.Cookies.Count%> cookies.

Click Here to retrieve these cookies.

Click Here to run the script in a new window.

Setting a cookie with ASP is pretty simple. The format is Response.Cookies("name")="value". That "value" can be either a JavaScript string or an ASP native type such as Request.Form("userEmail").

Response Cookie Keys:

If on the first page of your ASP application Response.Cookies("myOnlyCookie") is set, and subsequently on page two of your application Response.Cookies("myOnlyCookie") is reassigned a second value, then only the second value will remain. The first value is lost in this circumstance.

The solution is to either use multiple cookies or to use multiple Keys in the SAME cookie.

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."

The Setting of one or more Keys is pretty simple. It follows this format: Response.Cookies("name")("key")="value". Again, the "value" can either be a JavaScript string or ASP native type. The advantage of using keys is that you can store multiple Key/Value pairs inside the very same cookie.

Request Cookies:

Generally you will find ASP cookie management to be far easier than Client Side JavaScript cookies. Down below is the script that retrieves the cookies.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
var firstCookie = Request.Cookies("firstCookie");
var secondCookie = Request.Cookies("secondCookie");
var thirdCookie2Keys = Request.Cookies("thirdCookie")("firstKey")
thirdCookie2Keys += " " + Request.Cookies("thirdCookie")("secondKey");
%>

There are <%=Request.Cookies.Count%> Cookies.

1) <%=firstCookie%>

2) <%=secondCookie%>

3) <%=thirdCookie2Keys%>

Click Here to see how we would sort cookies
if we didn't know their names.

Click Here to run the script in a new window.

Do I even need to explain "firstCookie" and "secondCookie"? It's so easy. However, I will have to have explain the retrieval of Keys in "thirdCookie".

We retrieve cookies in almost exactly the same way that we set them, and that goes for Keys as well. If you keep track of your Key names, then retrieving their values is pretty easy.

var thirdCookieFirstKey = Request.Cookies("thirdCookie")("firstKey")

Deleting Cookies:

To delete a cookie, give it an expiration date in the past. The following is not in our examples, but it would work.

var Yesterday=new Date()
Yesterday.setDate(Yesterday.getDate() - 1)
myExpire = (Yesterday.getMonth() + 1) + "/" + Yesterday.getDate()
myExpire += "/" + Yesterday.getFullYear()
Response.Cookies("firstCookie").Expires=myExpire

Cookie Crumbs:

What if you lose track of your cookie names? What if you lose your Keys? First of all, don't do that. But secondly, we have options.

We can use a VBScript Function with a for/each loop. We can use Javascript's new Enumerator( ) or we can use a pair of for Loops. We, however, cannot use JavaScript's for/in loop. This means we have to be creative.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
%>


<%
Response.Write("Let's use a VBScript function to ")
Response.Write("sort out the Cookies and Keys.

\r")
var longCookie = forEachCookie()
if (longCookie)
{
longCookie = longCookie.split("; ")
for (i=0;i<=longCookie.length-1;i++)
{
Response.Write(longCookie[ i ] + "
\r")
}
}
Response.Write("
\r")

Response.Write("Let's use new Enumerator( ) to ")
Response.Write("sort out the Cookies and Keys.

\r")
var myEnum = new Enumerator(Request.Cookies);
for (myEnum; !myEnum.atEnd() ; myEnum.moveNext() )
{
Response.Write(myEnum.item() + "=")
n=Request.Cookies(myEnum.item()).Count
if (n)
{
for (o=1;o<=n;o++)
{
Response.Write(Request.Cookies(myEnum.item())(o) + " ")
}
//Begin alternate method of using Enumerator()
Response.Write("
\rOR... ")
Response.Write(myEnum.item() + "=")
Response.Write(unescape(Request.Cookies(myEnum.item())))
//End alternate method
}
else
{
Response.Write(Request.Cookies(myEnum.item()))
}
Response.Write("
\r")
}
Response.Write("
\r")

Response.Write("Let's use a pair of JavaScript loops to ")
Response.Write("sort out the Cookies and Keys.

\r")
a=Request.Cookies.Count
for (b=1;b<=a;b++)
{
d = Request.Cookies(b).Count
if (d)
{
for (c=1;c<=d;c++)
{
Response.Write(Request.Cookies(b)(c) + " ")
}
Response.Write("
\r")
}
else
{
Response.Write(Request.Cookies(b) + "
\r")
}
}
%>

Click Here to run the script in a new window.

We do the same job three times. You decide for yourself which one you like best. In the first example you can plainly see from the script, I ask a VBScript function to find and break down all the cookies. I then output the data back to the waiting JavaScript variable.

var longCookie = forEachCookie()

What can I say? Don't lose track of your cookies and don't lose track of your Keys. Otherwise you might have to get a VBScript slim jim.

The new Enumerator() is okay. I use Enumerator two different ways; one way fails to capture the Key names, and the other way successfully captures the key names (but it needs unescape() to get the Key values to print normally).

In round three, I use a pair of for loops, but they're not as functional as for/in would be. (Notice the lack of Key names.)

Misc. Notes:

We didn't use new String( ) in this lesson. But remember, if you want to manipulate the cookie values inside JavaScript functions or methods, then you will need new String().

var firstCookie = new String(Request.Cookies("firstCookie") )
firstCookie = firstCookie.toUpperCase()

Also, if you were to use Client Side scripting to locate cookies, you would have noticed that there is an extra cookie. ASP keeps track of its sessions using a cookie.



------------------------------- 10 -----------------------------------

lobal ASA

Global.asa:

First of all, what is a global.asa? It's an optional script file that holds certain "global" information that you can access through the entire ASP appliciation. The global.asa is a plain text file saved with the .asa extension.

You should only have one global.asa and it should go in your top level directory.

Below is an example global.asa file. Don't try to understand the script just yet. We'll get to the specifics in the next two lessons.







List of Can Do's:

There are four things you can do with a global.asa.

1) Object Declarations
2) Application Events
3) Session Events
4) Library Reference.

I don't expect you understand any of that yet. Just remember, there are only a few things we can do with the global.asa. Let's move on to lesson 11.



------------------------------- 11 -----------------------------------

pplication Object

Overview:

The Application Object represents a collection of ASP pages. The Application object has zero (0) properties, two (2) collections, two (2) methods, and two (2) events.

Get Started:

Below are a couple scripts for lesson11.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>


Would you like to chose the official Application color?





No, click here.

Click Here to run script11.asp in a new window. Below is script11a.asp.

<%@LANGUAGE="JavaScript"%>

<%
Application.Lock()
var OfficialColor = new String( Request.Form("OfficialColor") )
if (OfficialColor=="red")
{
Application("OfficialColor") = "red"
}
if (OfficialColor=="white")
{
Application("OfficialColor") = "white"
}
if (OfficialColor=="blue")
{
Application("OfficialColor") = "blue"
}
if (OfficialColor=="undefined")
{
//Do nothing. Just leave the color alone.
}
Application.Unlock()
%>
">

The official application color is <%=Application("OfficialColor")%>.




Application Collections:

The two collections are Contents and StaticObjects. StaticObjects come in the form of the flag. That's done in the global.asa that we saw in Lesson 09. I'll demonstrate it again down below.

By contrast, the Contents collection is demonstrated above. It allows you to set and retrieve variables with Application scope. The format for setting an Application variable is Application.Contents("VariableName")="VariableValue". However, since Contents is the default Collection, we have a little shortcut for setting Application variables. The shortcut goes like this: Application("VariableName")="VariableValue".

Share the Variable:

One last thought on Application Variables. The application variable is shared by all visitors. Let's say that you and I are on the same ASP web site at the same time. If you set the background color to white in script11.asp, then I will see "white" as the official color if I go directly to script11a.asp. Application Variables are by no means the most efficient means of passing information from one user to another.

No Apartment Model:

You may notice that the example above seems to be inefficient. Why not just directly assign Application("OfficialColor") = Request.Form("OfficialColor")? Because we can't. By design, the newer (and updated) versions of Microsoft server software intentionally do not support Apartment Model Behavior.

Application Methods:

The two Application Methods are Lock() and Unlock(). Lock() blocks all other users from changing the Application variables. Unlock() releases control so that other users can change it. That's important on a larger site where multiple users may be trying to access the same page at the same time.

Application Events:

The two Application events are Application_OnStart() and Application_OnEnd(). These events are accessed in the global.asa. Let's repeat that script from lesson 09.







Misc. Items:

Application.Contents has two methods of its own. Application.Contents.Remove("VariableName") and Application.Contents.RemoveAll().

You'll notice there are also Session Events in the global.asa. We'll deal with those in Lesson 12. You'll also notice a call to the ADO Library. We'll talk about that when we get to databases.


------------------------------- 12 -----------------------------------

ession Object

Overview:

The Session Object is how you track a single user across many pages. It has four (4) properties, two (2) collections, one (1) method, and two (2) events.

Get Started:

In this series of examples we will create a password system. We will use the Session Object to track whether or not a user is authorized to view certain pages. Below are several scripts for lesson12. Look at them, play with, and then read the explanations that come further down the page.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

To play along with our password page, put in a user name and a password.


The correct user name is guest.

And the correct password is also guest.


User:

Pass:





Click Here to run script12.asp in a new window. Below is script12a.asp.

<%@LANGUAGE="JavaScript"%>
<%
var userName=new String(Request.Form("userName"))
var userPassword=new String(Request.Form("userPassword"))
if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}
else
{
Session("Authorized")=false
%>

You did not supply the correct Name & Password.

Click here to log in.

<%
} //end else statement
%>

We'll skip over script12b.asp entirely because it's almost exactly the same as script12c.asp. Down below is script12c.asp.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
%>

The second of two pages that are password protected.

Click Here to log out.

<%
} //end of else statement
%>

Above is script12c.asp, which is the second of two password-protected pages. Below is script12.asp, which is the logout page.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
var SessionID=Session.SessionID
Session.Abandon()
%>

You have sucessfully logged out.

This was session <%=SessionID%>.


Now try a link to one of the
pages you've already visited.


script12b.asp

script12c.asp

script12d.asp


<%
} //end of else statement
%>

A Quick Explanation:

After all that, the last thing you want to see is another grey box full of code. Sorry to do it one more time but, the keystone to this system is in script12a.asp. I've reprinted it down below.

if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}

Any page can now be turned into a password protected page with the following line: if (Session("Authorized")!=true). Session Variables are part of the Session Collections. Let's talk about them.

Session Collections:

The two Session Collections are Session.Contents and Session.StaticObjects. They parallel the Application.Contents and Application.StaticObjects.

Using Session.Contents("someVariable")="someValue" we can set Session Variables. These variables allow us to carry values from one page to the next. Since Contents is the default collection we can use a little shortcut. It goes like this: Session("someVariable")="someValue".

The shortcut is what you saw in the scripts above.

Session.Contents has two methods of its own. They are Session.Contents.Remove("variableName") and Session.Contents.RemoveAll().

We did not demonstrate StaticObjects in the scripts above. It comes in the form of the flag (set for Session scope).

No Sharing:

Remember how Application variables could be shared by all viewers on your ASP web site? That's not so with Session Variables. They are private; Session Variables are to be accessed only by one user.

Session.Abandon( ):

My bet is you could figure out Session.Abandon() without any explanation. However, let me just state for the record that Session.Abandon() ends the user's session and releases the Session Variables from memory.

Session Properties:

Let's briefly discuss two properties you are not likely to use. Session.CodePage lets you call for foreign character sets, like Chinese or Russian. Session.LCID is a location identifier. It determines the time zone and language for the server. Don't mess with it.

Now let's move on to something you might actually use from time to time. Session.SessionID is a read-only property generated by the server, and assigned to one specific user during one specific session. The SessionID follows the user from the beginning of the session until the end.

Session.Timeout is the number of minutes that a user can be idle before the Server ends the user's individual session and reclaims the memory that was allocated to Session Variables. (Session.Timeout is demonstrated in the global.asa in lesson 10.)

Session Events:

The two Session events are Session_OnStart() and Session_OnEnd(). These events are accessed in the global.asa. You can see an example of global.asa in lesson 10.

What's Next:

We've seen in the last two lessons that Apartment Model Behavior is strictly forbidden in the Application Intrinsic Object. (It's not forbidden in the Session Object, but it is restricted.) So how do we store values (functions in particular) for reuse in many scripts? That is the subject of Lesson 13.


------------------------------- 13 -----------------------------------

nclude Files

Server Side Includes:

Experienced JavaScript programmers know that code reuse is good. Experienced JavaScript programmers also know that JavaScript functions are data types.

So, we should be able to store a JavaScript function inside a Session Variable or an Application Variable, right? Unfortunately, no. The way to reuse JavaScript functions across many pages is to use SSI: Server Side Includes.

<%@LANGUAGE="JavaScript"%>


ASP JavaScript Lessons(8-14)-speakitnow-ChinaUnix博客
  • 博客访问: 5547947
  • 博文数量: 915
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 5216
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-15 17:17
文章分类

全部博文(915)

文章存档

2011年(1)

2008年(134)

2007年(287)

2006年(493)

我的朋友
微信关注

IT168企业级官微



微信号:IT168qiye



系统架构师大会



微信号:SACC2013

订阅
热词专题
ASP JavaScript Lessons(8-14) 2006-12-31 14:48:22

分类: Java

-------------------------------- 8 -----------------------------------

The Request Object

Request Object:

Request has five (5) Collections, one (1) Property, and one (1) Method. You'll use the Collections far more than the property or the method.

Request Collections:

Below is a table of the Request Collections and descriptions of how they are used.

Request Collections
ClientCertificateRequest.ClientCertificate("Key[Field]")
Client security info for SSL encryption
CookiesRequest.Cookies("cookieName")
Holds cookie value stored on the client
FormRequest.Form("formName")
Holds value sent via HTML Form
QueryStringRequest.QueryString("keyName")
Name/Value pair appended to the end of the URL
ServerVariablesRequest.ServerVariables("variableName")
Hold values sent in the HTTP Headers

ClientCertificate:

Request.ClientCertificate is used with S.S.L. (Secure Sockets Layer). It is beyond the scope of this web site.

Cookies:

We will learn Request.Cookies and Response.Cookies together in Lesson 08. Please be patient.

Form:

Request.Form is probably the workhorse of the Request Collections. The first script is a repeat from Lesson 03.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

Type something into the text box and submit it.



How Much Money do you make each month?






Click Here to run script08.asp in a new window. It posts information to script08a.asp which is found below. In turn, script08a.asp posts information to script08b.asp which is also found below.

<%@LANGUAGE="JavaScript"%>
<%
var WebPageVariable = new String( Request.Form("WebPageVariable") )
WebPageVariable = WebPageVariable.toUpperCase();

var monthlySalary = new String( Request.Form("monthlySalary") )
monthlySalary = monthlySalary.toLowerCase();
%>

The Web Page Variable you typed is: <%=WebPageVariable%>

The monthly salary you listed is: <%=monthlySalary%>



Click the button to see Query Strings




We'll be using Request.Form when we "Post" an HTML form to the server. Notice that the NAME attribute in the HTML form corresponds to the "name" in Request.Form("name"). To be more specific, corresponds with Request.Form("WebPageVariable"). We already talked about the need for the new String( ) constructor back in Lesson 03.

QueryString:

We'll be using Request.QueryString when we use an HTML form to "Get" a page from the server. Request.QueryString() is very similar to Request.Form(). Take a look at script08b.asp which I printed below.

<%@LANGUAGE="JavaScript"%>
<%
var QueryVariable = new String( Request.QueryString("QueryVariable") )
%>

The QueryString Value is: <%=QueryVariable%>

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>
Click Here
for the link to script08b.asp?QueryVariable=<%=QueryVariable%>
<%
} //closing bracket for if statement.
%>

If you haven't already, Click Here to run script08.asp in a new window. Cycle through all the forms and links, and then come back.

You can use Request.QueryString in two different ways. You can either use an HTML form to "Get" a page from the server, which will generate a query string. Or you can manually build a query string and add it to the backside of a link. We'll dissect script08b.asp from top to bottom.

var QueryVariable = new String( Request.QueryString("QueryVariable") )

The line above in script08b.asp corresponds to the line below from script08a.asp


The NAME="someName" in the HTML form becomes the Request.QueryString("someName") on the next page.

About half way into script08b.asp are the lines I reprinted below.

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>

We've already converted Request.QueryString() into a JavaScript string at the top of the script. So, now we can do a string comparison.

If the QueryVariable hasn't already been set equal to "Lesson 08's new Query!" then we do that. Then we use the escape( ) method to convert white space and special characters into Unicode. (URL's should contain neither whitespace, nor most special characters.)

In lesson 14 we'll see a better way to encode URL's. When we study the Server Object, we'll see Server.URLEncode(). But for now, just know that escape() works.

You can have more than one QueryString on each page. If you lose count of your QueryStrings, then you use Request.QueryString.Count to tell you the number.

The Request Shortcut:

Request.Form() and Request.QueryString() share a shortcut. Request.Form("WebPageVariable") can be abbreviated as Request("WebPageVariable") and Request.QueryString("QueryVariable") can be abbreviated as Request("QueryVariable").

ServerVariables:

Server Variables represent the HTTP Headers sent to the server by the client. I won't demonstrate them all, because there are too many.

<%@LANGUAGE="JavaScript"%>










ALL_RAW<%=Request.ServerVariables("ALL_RAW")%>
REMOTE_ADDR<%=Request.ServerVariables("REMOTE_ADDR")%>
HTTP_USER_AGENT<%=Request.ServerVariables("HTTP_USER_AGENT")%>
URL<%=Request.ServerVariables("URL")%>


Click Here to run the script in a new window.

Demonstrated above are four (4) server variables. There are (give or take) about 50 server variables available. You can look up the full list of server variables for yourself on the internet.

Misc. Notes:

Request.BinaryRead() is the lone method and TotalBytes is the lone property. Request.BinaryRead(Request.TotalBytes) retrieves data from an HTML form using "POST." You must supply the TotalBytes as an argument. It stores the data into an array. BinaryRead cannot be used at the same time as Request.Form().

Next Stop, Cookies:

The only Request Collection I did not cover was Cookies. I want to cover Request.Cookies and Response.Cookies side by side. So we'll do that in Lesson 09.


-------------------------------- 9 -----------------------------------

ookies and Cookies

Response Cookies in General:

We'll start with the Response Cookies collection. I don't think it could be any easier. You simply put the name of the cookie in the argument. The corresponding value is a string. The only time it gets complicated is when you use keys (which I demonstrate below).

<%@LANGUAGE="JavaScript"%>
<%
var Tomorrow=new Date()
Tomorrow.setDate(Tomorrow.getDate() + 1)
myExpire = (Tomorrow.getMonth() + 1) + "/" + Tomorrow.getDate()
myExpire += "/" + Tomorrow.getFullYear()

Response.Cookies("firstCookie") = "I like cookies."
Response.Cookies("firstCookie").Expires=myExpire

Response.Cookies("secondCookie") = "ASP Cookies Are Easy."
Response.Cookies("secondCookie").Expires=myExpire

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."
Response.Cookies("thirdCookie").Expires=myExpire
%>


We're just setting <%=Response.Cookies.Count%> cookies.

Click Here to retrieve these cookies.

Click Here to run the script in a new window.

Setting a cookie with ASP is pretty simple. The format is Response.Cookies("name")="value". That "value" can be either a JavaScript string or an ASP native type such as Request.Form("userEmail").

Response Cookie Keys:

If on the first page of your ASP application Response.Cookies("myOnlyCookie") is set, and subsequently on page two of your application Response.Cookies("myOnlyCookie") is reassigned a second value, then only the second value will remain. The first value is lost in this circumstance.

The solution is to either use multiple cookies or to use multiple Keys in the SAME cookie.

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."

The Setting of one or more Keys is pretty simple. It follows this format: Response.Cookies("name")("key")="value". Again, the "value" can either be a JavaScript string or ASP native type. The advantage of using keys is that you can store multiple Key/Value pairs inside the very same cookie.

Request Cookies:

Generally you will find ASP cookie management to be far easier than Client Side JavaScript cookies. Down below is the script that retrieves the cookies.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
var firstCookie = Request.Cookies("firstCookie");
var secondCookie = Request.Cookies("secondCookie");
var thirdCookie2Keys = Request.Cookies("thirdCookie")("firstKey")
thirdCookie2Keys += " " + Request.Cookies("thirdCookie")("secondKey");
%>

There are <%=Request.Cookies.Count%> Cookies.

1) <%=firstCookie%>

2) <%=secondCookie%>

3) <%=thirdCookie2Keys%>

Click Here to see how we would sort cookies
if we didn't know their names.

Click Here to run the script in a new window.

Do I even need to explain "firstCookie" and "secondCookie"? It's so easy. However, I will have to have explain the retrieval of Keys in "thirdCookie".

We retrieve cookies in almost exactly the same way that we set them, and that goes for Keys as well. If you keep track of your Key names, then retrieving their values is pretty easy.

var thirdCookieFirstKey = Request.Cookies("thirdCookie")("firstKey")

Deleting Cookies:

To delete a cookie, give it an expiration date in the past. The following is not in our examples, but it would work.

var Yesterday=new Date()
Yesterday.setDate(Yesterday.getDate() - 1)
myExpire = (Yesterday.getMonth() + 1) + "/" + Yesterday.getDate()
myExpire += "/" + Yesterday.getFullYear()
Response.Cookies("firstCookie").Expires=myExpire

Cookie Crumbs:

What if you lose track of your cookie names? What if you lose your Keys? First of all, don't do that. But secondly, we have options.

We can use a VBScript Function with a for/each loop. We can use Javascript's new Enumerator( ) or we can use a pair of for Loops. We, however, cannot use JavaScript's for/in loop. This means we have to be creative.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
%>


<%
Response.Write("Let's use a VBScript function to ")
Response.Write("sort out the Cookies and Keys.

\r")
var longCookie = forEachCookie()
if (longCookie)
{
longCookie = longCookie.split("; ")
for (i=0;i<=longCookie.length-1;i++)
{
Response.Write(longCookie[ i ] + "
\r")
}
}
Response.Write("
\r")

Response.Write("Let's use new Enumerator( ) to ")
Response.Write("sort out the Cookies and Keys.

\r")
var myEnum = new Enumerator(Request.Cookies);
for (myEnum; !myEnum.atEnd() ; myEnum.moveNext() )
{
Response.Write(myEnum.item() + "=")
n=Request.Cookies(myEnum.item()).Count
if (n)
{
for (o=1;o<=n;o++)
{
Response.Write(Request.Cookies(myEnum.item())(o) + " ")
}
//Begin alternate method of using Enumerator()
Response.Write("
\rOR... ")
Response.Write(myEnum.item() + "=")
Response.Write(unescape(Request.Cookies(myEnum.item())))
//End alternate method
}
else
{
Response.Write(Request.Cookies(myEnum.item()))
}
Response.Write("
\r")
}
Response.Write("
\r")

Response.Write("Let's use a pair of JavaScript loops to ")
Response.Write("sort out the Cookies and Keys.

\r")
a=Request.Cookies.Count
for (b=1;b<=a;b++)
{
d = Request.Cookies(b).Count
if (d)
{
for (c=1;c<=d;c++)
{
Response.Write(Request.Cookies(b)(c) + " ")
}
Response.Write("
\r")
}
else
{
Response.Write(Request.Cookies(b) + "
\r")
}
}
%>

Click Here to run the script in a new window.

We do the same job three times. You decide for yourself which one you like best. In the first example you can plainly see from the script, I ask a VBScript function to find and break down all the cookies. I then output the data back to the waiting JavaScript variable.

var longCookie = forEachCookie()

What can I say? Don't lose track of your cookies and don't lose track of your Keys. Otherwise you might have to get a VBScript slim jim.

The new Enumerator() is okay. I use Enumerator two different ways; one way fails to capture the Key names, and the other way successfully captures the key names (but it needs unescape() to get the Key values to print normally).

In round three, I use a pair of for loops, but they're not as functional as for/in would be. (Notice the lack of Key names.)

Misc. Notes:

We didn't use new String( ) in this lesson. But remember, if you want to manipulate the cookie values inside JavaScript functions or methods, then you will need new String().

var firstCookie = new String(Request.Cookies("firstCookie") )
firstCookie = firstCookie.toUpperCase()

Also, if you were to use Client Side scripting to locate cookies, you would have noticed that there is an extra cookie. ASP keeps track of its sessions using a cookie.



------------------------------- 10 -----------------------------------

lobal ASA

Global.asa:

First of all, what is a global.asa? It's an optional script file that holds certain "global" information that you can access through the entire ASP appliciation. The global.asa is a plain text file saved with the .asa extension.

You should only have one global.asa and it should go in your top level directory.

Below is an example global.asa file. Don't try to understand the script just yet. We'll get to the specifics in the next two lessons.







List of Can Do's:

There are four things you can do with a global.asa.

1) Object Declarations
2) Application Events
3) Session Events
4) Library Reference.

I don't expect you understand any of that yet. Just remember, there are only a few things we can do with the global.asa. Let's move on to lesson 11.



------------------------------- 11 -----------------------------------

pplication Object

Overview:

The Application Object represents a collection of ASP pages. The Application object has zero (0) properties, two (2) collections, two (2) methods, and two (2) events.

Get Started:

Below are a couple scripts for lesson11.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>


Would you like to chose the official Application color?





No, click here.

Click Here to run script11.asp in a new window. Below is script11a.asp.

<%@LANGUAGE="JavaScript"%>

<%
Application.Lock()
var OfficialColor = new String( Request.Form("OfficialColor") )
if (OfficialColor=="red")
{
Application("OfficialColor") = "red"
}
if (OfficialColor=="white")
{
Application("OfficialColor") = "white"
}
if (OfficialColor=="blue")
{
Application("OfficialColor") = "blue"
}
if (OfficialColor=="undefined")
{
//Do nothing. Just leave the color alone.
}
Application.Unlock()
%>
">

The official application color is <%=Application("OfficialColor")%>.




Application Collections:

The two collections are Contents and StaticObjects. StaticObjects come in the form of the flag. That's done in the global.asa that we saw in Lesson 09. I'll demonstrate it again down below.

By contrast, the Contents collection is demonstrated above. It allows you to set and retrieve variables with Application scope. The format for setting an Application variable is Application.Contents("VariableName")="VariableValue". However, since Contents is the default Collection, we have a little shortcut for setting Application variables. The shortcut goes like this: Application("VariableName")="VariableValue".

Share the Variable:

One last thought on Application Variables. The application variable is shared by all visitors. Let's say that you and I are on the same ASP web site at the same time. If you set the background color to white in script11.asp, then I will see "white" as the official color if I go directly to script11a.asp. Application Variables are by no means the most efficient means of passing information from one user to another.

No Apartment Model:

You may notice that the example above seems to be inefficient. Why not just directly assign Application("OfficialColor") = Request.Form("OfficialColor")? Because we can't. By design, the newer (and updated) versions of Microsoft server software intentionally do not support Apartment Model Behavior.

Application Methods:

The two Application Methods are Lock() and Unlock(). Lock() blocks all other users from changing the Application variables. Unlock() releases control so that other users can change it. That's important on a larger site where multiple users may be trying to access the same page at the same time.

Application Events:

The two Application events are Application_OnStart() and Application_OnEnd(). These events are accessed in the global.asa. Let's repeat that script from lesson 09.







Misc. Items:

Application.Contents has two methods of its own. Application.Contents.Remove("VariableName") and Application.Contents.RemoveAll().

You'll notice there are also Session Events in the global.asa. We'll deal with those in Lesson 12. You'll also notice a call to the ADO Library. We'll talk about that when we get to databases.


------------------------------- 12 -----------------------------------

ession Object

Overview:

The Session Object is how you track a single user across many pages. It has four (4) properties, two (2) collections, one (1) method, and two (2) events.

Get Started:

In this series of examples we will create a password system. We will use the Session Object to track whether or not a user is authorized to view certain pages. Below are several scripts for lesson12. Look at them, play with, and then read the explanations that come further down the page.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

To play along with our password page, put in a user name and a password.


The correct user name is guest.

And the correct password is also guest.


User:

Pass:





Click Here to run script12.asp in a new window. Below is script12a.asp.

<%@LANGUAGE="JavaScript"%>
<%
var userName=new String(Request.Form("userName"))
var userPassword=new String(Request.Form("userPassword"))
if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}
else
{
Session("Authorized")=false
%>

You did not supply the correct Name & Password.

Click here to log in.

<%
} //end else statement
%>

We'll skip over script12b.asp entirely because it's almost exactly the same as script12c.asp. Down below is script12c.asp.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
%>

The second of two pages that are password protected.

Click Here to log out.

<%
} //end of else statement
%>

Above is script12c.asp, which is the second of two password-protected pages. Below is script12.asp, which is the logout page.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
var SessionID=Session.SessionID
Session.Abandon()
%>

You have sucessfully logged out.

This was session <%=SessionID%>.


Now try a link to one of the
pages you've already visited.


script12b.asp

script12c.asp

script12d.asp


<%
} //end of else statement
%>

A Quick Explanation:

After all that, the last thing you want to see is another grey box full of code. Sorry to do it one more time but, the keystone to this system is in script12a.asp. I've reprinted it down below.

if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}

Any page can now be turned into a password protected page with the following line: if (Session("Authorized")!=true). Session Variables are part of the Session Collections. Let's talk about them.

Session Collections:

The two Session Collections are Session.Contents and Session.StaticObjects. They parallel the Application.Contents and Application.StaticObjects.

Using Session.Contents("someVariable")="someValue" we can set Session Variables. These variables allow us to carry values from one page to the next. Since Contents is the default collection we can use a little shortcut. It goes like this: Session("someVariable")="someValue".

The shortcut is what you saw in the scripts above.

Session.Contents has two methods of its own. They are Session.Contents.Remove("variableName") and Session.Contents.RemoveAll().

We did not demonstrate StaticObjects in the scripts above. It comes in the form of the flag (set for Session scope).

No Sharing:

Remember how Application variables could be shared by all viewers on your ASP web site? That's not so with Session Variables. They are private; Session Variables are to be accessed only by one user.

Session.Abandon( ):

My bet is you could figure out Session.Abandon() without any explanation. However, let me just state for the record that Session.Abandon() ends the user's session and releases the Session Variables from memory.

Session Properties:

Let's briefly discuss two properties you are not likely to use. Session.CodePage lets you call for foreign character sets, like Chinese or Russian. Session.LCID is a location identifier. It determines the time zone and language for the server. Don't mess with it.

Now let's move on to something you might actually use from time to time. Session.SessionID is a read-only property generated by the server, and assigned to one specific user during one specific session. The SessionID follows the user from the beginning of the session until the end.

Session.Timeout is the number of minutes that a user can be idle before the Server ends the user's individual session and reclaims the memory that was allocated to Session Variables. (Session.Timeout is demonstrated in the global.asa in lesson 10.)

Session Events:

The two Session events are Session_OnStart() and Session_OnEnd(). These events are accessed in the global.asa. You can see an example of global.asa in lesson 10.

What's Next:

We've seen in the last two lessons that Apartment Model Behavior is strictly forbidden in the Application Intrinsic Object. (It's not forbidden in the Session Object, but it is restricted.) So how do we store values (functions in particular) for reuse in many scripts? That is the subject of Lesson 13.


------------------------------- 13 -----------------------------------

nclude Files

Server Side Includes:

Experienced JavaScript programmers know that code reuse is good. Experienced JavaScript programmers also know that JavaScript functions are data types.

So, we should be able to store a JavaScript function inside a Session Variable or an Application Variable, right? Unfortunately, no. The way to reuse JavaScript functions across many pages is to use SSI: Server Side Includes.

<%@LANGUAGE="JavaScript"%>


ASP JavaScript Lessons(8-14)-speakitnow-ChinaUnix博客
  • 博客访问: 5547948
  • 博文数量: 915
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 5216
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-15 17:17
文章分类

全部博文(915)

文章存档

2011年(1)

2008年(134)

2007年(287)

2006年(493)

我的朋友
微信关注

IT168企业级官微



微信号:IT168qiye



系统架构师大会



微信号:SACC2013

订阅
热词专题
ASP JavaScript Lessons(8-14) 2006-12-31 14:48:22

分类: Java

-------------------------------- 8 -----------------------------------

The Request Object

Request Object:

Request has five (5) Collections, one (1) Property, and one (1) Method. You'll use the Collections far more than the property or the method.

Request Collections:

Below is a table of the Request Collections and descriptions of how they are used.

Request Collections
ClientCertificateRequest.ClientCertificate("Key[Field]")
Client security info for SSL encryption
CookiesRequest.Cookies("cookieName")
Holds cookie value stored on the client
FormRequest.Form("formName")
Holds value sent via HTML Form
QueryStringRequest.QueryString("keyName")
Name/Value pair appended to the end of the URL
ServerVariablesRequest.ServerVariables("variableName")
Hold values sent in the HTTP Headers

ClientCertificate:

Request.ClientCertificate is used with S.S.L. (Secure Sockets Layer). It is beyond the scope of this web site.

Cookies:

We will learn Request.Cookies and Response.Cookies together in Lesson 08. Please be patient.

Form:

Request.Form is probably the workhorse of the Request Collections. The first script is a repeat from Lesson 03.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

Type something into the text box and submit it.



How Much Money do you make each month?






Click Here to run script08.asp in a new window. It posts information to script08a.asp which is found below. In turn, script08a.asp posts information to script08b.asp which is also found below.

<%@LANGUAGE="JavaScript"%>
<%
var WebPageVariable = new String( Request.Form("WebPageVariable") )
WebPageVariable = WebPageVariable.toUpperCase();

var monthlySalary = new String( Request.Form("monthlySalary") )
monthlySalary = monthlySalary.toLowerCase();
%>

The Web Page Variable you typed is: <%=WebPageVariable%>

The monthly salary you listed is: <%=monthlySalary%>



Click the button to see Query Strings




We'll be using Request.Form when we "Post" an HTML form to the server. Notice that the NAME attribute in the HTML form corresponds to the "name" in Request.Form("name"). To be more specific, corresponds with Request.Form("WebPageVariable"). We already talked about the need for the new String( ) constructor back in Lesson 03.

QueryString:

We'll be using Request.QueryString when we use an HTML form to "Get" a page from the server. Request.QueryString() is very similar to Request.Form(). Take a look at script08b.asp which I printed below.

<%@LANGUAGE="JavaScript"%>
<%
var QueryVariable = new String( Request.QueryString("QueryVariable") )
%>

The QueryString Value is: <%=QueryVariable%>

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>
Click Here
for the link to script08b.asp?QueryVariable=<%=QueryVariable%>
<%
} //closing bracket for if statement.
%>

If you haven't already, Click Here to run script08.asp in a new window. Cycle through all the forms and links, and then come back.

You can use Request.QueryString in two different ways. You can either use an HTML form to "Get" a page from the server, which will generate a query string. Or you can manually build a query string and add it to the backside of a link. We'll dissect script08b.asp from top to bottom.

var QueryVariable = new String( Request.QueryString("QueryVariable") )

The line above in script08b.asp corresponds to the line below from script08a.asp


The NAME="someName" in the HTML form becomes the Request.QueryString("someName") on the next page.

About half way into script08b.asp are the lines I reprinted below.

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>

We've already converted Request.QueryString() into a JavaScript string at the top of the script. So, now we can do a string comparison.

If the QueryVariable hasn't already been set equal to "Lesson 08's new Query!" then we do that. Then we use the escape( ) method to convert white space and special characters into Unicode. (URL's should contain neither whitespace, nor most special characters.)

In lesson 14 we'll see a better way to encode URL's. When we study the Server Object, we'll see Server.URLEncode(). But for now, just know that escape() works.

You can have more than one QueryString on each page. If you lose count of your QueryStrings, then you use Request.QueryString.Count to tell you the number.

The Request Shortcut:

Request.Form() and Request.QueryString() share a shortcut. Request.Form("WebPageVariable") can be abbreviated as Request("WebPageVariable") and Request.QueryString("QueryVariable") can be abbreviated as Request("QueryVariable").

ServerVariables:

Server Variables represent the HTTP Headers sent to the server by the client. I won't demonstrate them all, because there are too many.

<%@LANGUAGE="JavaScript"%>










ALL_RAW<%=Request.ServerVariables("ALL_RAW")%>
REMOTE_ADDR<%=Request.ServerVariables("REMOTE_ADDR")%>
HTTP_USER_AGENT<%=Request.ServerVariables("HTTP_USER_AGENT")%>
URL<%=Request.ServerVariables("URL")%>


Click Here to run the script in a new window.

Demonstrated above are four (4) server variables. There are (give or take) about 50 server variables available. You can look up the full list of server variables for yourself on the internet.

Misc. Notes:

Request.BinaryRead() is the lone method and TotalBytes is the lone property. Request.BinaryRead(Request.TotalBytes) retrieves data from an HTML form using "POST." You must supply the TotalBytes as an argument. It stores the data into an array. BinaryRead cannot be used at the same time as Request.Form().

Next Stop, Cookies:

The only Request Collection I did not cover was Cookies. I want to cover Request.Cookies and Response.Cookies side by side. So we'll do that in Lesson 09.


-------------------------------- 9 -----------------------------------

ookies and Cookies

Response Cookies in General:

We'll start with the Response Cookies collection. I don't think it could be any easier. You simply put the name of the cookie in the argument. The corresponding value is a string. The only time it gets complicated is when you use keys (which I demonstrate below).

<%@LANGUAGE="JavaScript"%>
<%
var Tomorrow=new Date()
Tomorrow.setDate(Tomorrow.getDate() + 1)
myExpire = (Tomorrow.getMonth() + 1) + "/" + Tomorrow.getDate()
myExpire += "/" + Tomorrow.getFullYear()

Response.Cookies("firstCookie") = "I like cookies."
Response.Cookies("firstCookie").Expires=myExpire

Response.Cookies("secondCookie") = "ASP Cookies Are Easy."
Response.Cookies("secondCookie").Expires=myExpire

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."
Response.Cookies("thirdCookie").Expires=myExpire
%>


We're just setting <%=Response.Cookies.Count%> cookies.

Click Here to retrieve these cookies.

Click Here to run the script in a new window.

Setting a cookie with ASP is pretty simple. The format is Response.Cookies("name")="value". That "value" can be either a JavaScript string or an ASP native type such as Request.Form("userEmail").

Response Cookie Keys:

If on the first page of your ASP application Response.Cookies("myOnlyCookie") is set, and subsequently on page two of your application Response.Cookies("myOnlyCookie") is reassigned a second value, then only the second value will remain. The first value is lost in this circumstance.

The solution is to either use multiple cookies or to use multiple Keys in the SAME cookie.

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."

The Setting of one or more Keys is pretty simple. It follows this format: Response.Cookies("name")("key")="value". Again, the "value" can either be a JavaScript string or ASP native type. The advantage of using keys is that you can store multiple Key/Value pairs inside the very same cookie.

Request Cookies:

Generally you will find ASP cookie management to be far easier than Client Side JavaScript cookies. Down below is the script that retrieves the cookies.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
var firstCookie = Request.Cookies("firstCookie");
var secondCookie = Request.Cookies("secondCookie");
var thirdCookie2Keys = Request.Cookies("thirdCookie")("firstKey")
thirdCookie2Keys += " " + Request.Cookies("thirdCookie")("secondKey");
%>

There are <%=Request.Cookies.Count%> Cookies.

1) <%=firstCookie%>

2) <%=secondCookie%>

3) <%=thirdCookie2Keys%>

Click Here to see how we would sort cookies
if we didn't know their names.

Click Here to run the script in a new window.

Do I even need to explain "firstCookie" and "secondCookie"? It's so easy. However, I will have to have explain the retrieval of Keys in "thirdCookie".

We retrieve cookies in almost exactly the same way that we set them, and that goes for Keys as well. If you keep track of your Key names, then retrieving their values is pretty easy.

var thirdCookieFirstKey = Request.Cookies("thirdCookie")("firstKey")

Deleting Cookies:

To delete a cookie, give it an expiration date in the past. The following is not in our examples, but it would work.

var Yesterday=new Date()
Yesterday.setDate(Yesterday.getDate() - 1)
myExpire = (Yesterday.getMonth() + 1) + "/" + Yesterday.getDate()
myExpire += "/" + Yesterday.getFullYear()
Response.Cookies("firstCookie").Expires=myExpire

Cookie Crumbs:

What if you lose track of your cookie names? What if you lose your Keys? First of all, don't do that. But secondly, we have options.

We can use a VBScript Function with a for/each loop. We can use Javascript's new Enumerator( ) or we can use a pair of for Loops. We, however, cannot use JavaScript's for/in loop. This means we have to be creative.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
%>


<%
Response.Write("Let's use a VBScript function to ")
Response.Write("sort out the Cookies and Keys.

\r")
var longCookie = forEachCookie()
if (longCookie)
{
longCookie = longCookie.split("; ")
for (i=0;i<=longCookie.length-1;i++)
{
Response.Write(longCookie[ i ] + "
\r")
}
}
Response.Write("
\r")

Response.Write("Let's use new Enumerator( ) to ")
Response.Write("sort out the Cookies and Keys.

\r")
var myEnum = new Enumerator(Request.Cookies);
for (myEnum; !myEnum.atEnd() ; myEnum.moveNext() )
{
Response.Write(myEnum.item() + "=")
n=Request.Cookies(myEnum.item()).Count
if (n)
{
for (o=1;o<=n;o++)
{
Response.Write(Request.Cookies(myEnum.item())(o) + " ")
}
//Begin alternate method of using Enumerator()
Response.Write("
\rOR... ")
Response.Write(myEnum.item() + "=")
Response.Write(unescape(Request.Cookies(myEnum.item())))
//End alternate method
}
else
{
Response.Write(Request.Cookies(myEnum.item()))
}
Response.Write("
\r")
}
Response.Write("
\r")

Response.Write("Let's use a pair of JavaScript loops to ")
Response.Write("sort out the Cookies and Keys.

\r")
a=Request.Cookies.Count
for (b=1;b<=a;b++)
{
d = Request.Cookies(b).Count
if (d)
{
for (c=1;c<=d;c++)
{
Response.Write(Request.Cookies(b)(c) + " ")
}
Response.Write("
\r")
}
else
{
Response.Write(Request.Cookies(b) + "
\r")
}
}
%>

Click Here to run the script in a new window.

We do the same job three times. You decide for yourself which one you like best. In the first example you can plainly see from the script, I ask a VBScript function to find and break down all the cookies. I then output the data back to the waiting JavaScript variable.

var longCookie = forEachCookie()

What can I say? Don't lose track of your cookies and don't lose track of your Keys. Otherwise you might have to get a VBScript slim jim.

The new Enumerator() is okay. I use Enumerator two different ways; one way fails to capture the Key names, and the other way successfully captures the key names (but it needs unescape() to get the Key values to print normally).

In round three, I use a pair of for loops, but they're not as functional as for/in would be. (Notice the lack of Key names.)

Misc. Notes:

We didn't use new String( ) in this lesson. But remember, if you want to manipulate the cookie values inside JavaScript functions or methods, then you will need new String().

var firstCookie = new String(Request.Cookies("firstCookie") )
firstCookie = firstCookie.toUpperCase()

Also, if you were to use Client Side scripting to locate cookies, you would have noticed that there is an extra cookie. ASP keeps track of its sessions using a cookie.



------------------------------- 10 -----------------------------------

lobal ASA

Global.asa:

First of all, what is a global.asa? It's an optional script file that holds certain "global" information that you can access through the entire ASP appliciation. The global.asa is a plain text file saved with the .asa extension.

You should only have one global.asa and it should go in your top level directory.

Below is an example global.asa file. Don't try to understand the script just yet. We'll get to the specifics in the next two lessons.







List of Can Do's:

There are four things you can do with a global.asa.

1) Object Declarations
2) Application Events
3) Session Events
4) Library Reference.

I don't expect you understand any of that yet. Just remember, there are only a few things we can do with the global.asa. Let's move on to lesson 11.



------------------------------- 11 -----------------------------------

pplication Object

Overview:

The Application Object represents a collection of ASP pages. The Application object has zero (0) properties, two (2) collections, two (2) methods, and two (2) events.

Get Started:

Below are a couple scripts for lesson11.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>


Would you like to chose the official Application color?





No, click here.

Click Here to run script11.asp in a new window. Below is script11a.asp.

<%@LANGUAGE="JavaScript"%>

<%
Application.Lock()
var OfficialColor = new String( Request.Form("OfficialColor") )
if (OfficialColor=="red")
{
Application("OfficialColor") = "red"
}
if (OfficialColor=="white")
{
Application("OfficialColor") = "white"
}
if (OfficialColor=="blue")
{
Application("OfficialColor") = "blue"
}
if (OfficialColor=="undefined")
{
//Do nothing. Just leave the color alone.
}
Application.Unlock()
%>
">

The official application color is <%=Application("OfficialColor")%>.




Application Collections:

The two collections are Contents and StaticObjects. StaticObjects come in the form of the flag. That's done in the global.asa that we saw in Lesson 09. I'll demonstrate it again down below.

By contrast, the Contents collection is demonstrated above. It allows you to set and retrieve variables with Application scope. The format for setting an Application variable is Application.Contents("VariableName")="VariableValue". However, since Contents is the default Collection, we have a little shortcut for setting Application variables. The shortcut goes like this: Application("VariableName")="VariableValue".

Share the Variable:

One last thought on Application Variables. The application variable is shared by all visitors. Let's say that you and I are on the same ASP web site at the same time. If you set the background color to white in script11.asp, then I will see "white" as the official color if I go directly to script11a.asp. Application Variables are by no means the most efficient means of passing information from one user to another.

No Apartment Model:

You may notice that the example above seems to be inefficient. Why not just directly assign Application("OfficialColor") = Request.Form("OfficialColor")? Because we can't. By design, the newer (and updated) versions of Microsoft server software intentionally do not support Apartment Model Behavior.

Application Methods:

The two Application Methods are Lock() and Unlock(). Lock() blocks all other users from changing the Application variables. Unlock() releases control so that other users can change it. That's important on a larger site where multiple users may be trying to access the same page at the same time.

Application Events:

The two Application events are Application_OnStart() and Application_OnEnd(). These events are accessed in the global.asa. Let's repeat that script from lesson 09.







Misc. Items:

Application.Contents has two methods of its own. Application.Contents.Remove("VariableName") and Application.Contents.RemoveAll().

You'll notice there are also Session Events in the global.asa. We'll deal with those in Lesson 12. You'll also notice a call to the ADO Library. We'll talk about that when we get to databases.


------------------------------- 12 -----------------------------------

ession Object

Overview:

The Session Object is how you track a single user across many pages. It has four (4) properties, two (2) collections, one (1) method, and two (2) events.

Get Started:

In this series of examples we will create a password system. We will use the Session Object to track whether or not a user is authorized to view certain pages. Below are several scripts for lesson12. Look at them, play with, and then read the explanations that come further down the page.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

To play along with our password page, put in a user name and a password.


The correct user name is guest.

And the correct password is also guest.


User:

Pass:





Click Here to run script12.asp in a new window. Below is script12a.asp.

<%@LANGUAGE="JavaScript"%>
<%
var userName=new String(Request.Form("userName"))
var userPassword=new String(Request.Form("userPassword"))
if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}
else
{
Session("Authorized")=false
%>

You did not supply the correct Name & Password.

Click here to log in.

<%
} //end else statement
%>

We'll skip over script12b.asp entirely because it's almost exactly the same as script12c.asp. Down below is script12c.asp.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
%>

The second of two pages that are password protected.

Click Here to log out.

<%
} //end of else statement
%>

Above is script12c.asp, which is the second of two password-protected pages. Below is script12.asp, which is the logout page.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
var SessionID=Session.SessionID
Session.Abandon()
%>

You have sucessfully logged out.

This was session <%=SessionID%>.


Now try a link to one of the
pages you've already visited.


script12b.asp

script12c.asp

script12d.asp


<%
} //end of else statement
%>

A Quick Explanation:

After all that, the last thing you want to see is another grey box full of code. Sorry to do it one more time but, the keystone to this system is in script12a.asp. I've reprinted it down below.

if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}

Any page can now be turned into a password protected page with the following line: if (Session("Authorized")!=true). Session Variables are part of the Session Collections. Let's talk about them.

Session Collections:

The two Session Collections are Session.Contents and Session.StaticObjects. They parallel the Application.Contents and Application.StaticObjects.

Using Session.Contents("someVariable")="someValue" we can set Session Variables. These variables allow us to carry values from one page to the next. Since Contents is the default collection we can use a little shortcut. It goes like this: Session("someVariable")="someValue".

The shortcut is what you saw in the scripts above.

Session.Contents has two methods of its own. They are Session.Contents.Remove("variableName") and Session.Contents.RemoveAll().

We did not demonstrate StaticObjects in the scripts above. It comes in the form of the flag (set for Session scope).

No Sharing:

Remember how Application variables could be shared by all viewers on your ASP web site? That's not so with Session Variables. They are private; Session Variables are to be accessed only by one user.

Session.Abandon( ):

My bet is you could figure out Session.Abandon() without any explanation. However, let me just state for the record that Session.Abandon() ends the user's session and releases the Session Variables from memory.

Session Properties:

Let's briefly discuss two properties you are not likely to use. Session.CodePage lets you call for foreign character sets, like Chinese or Russian. Session.LCID is a location identifier. It determines the time zone and language for the server. Don't mess with it.

Now let's move on to something you might actually use from time to time. Session.SessionID is a read-only property generated by the server, and assigned to one specific user during one specific session. The SessionID follows the user from the beginning of the session until the end.

Session.Timeout is the number of minutes that a user can be idle before the Server ends the user's individual session and reclaims the memory that was allocated to Session Variables. (Session.Timeout is demonstrated in the global.asa in lesson 10.)

Session Events:

The two Session events are Session_OnStart() and Session_OnEnd(). These events are accessed in the global.asa. You can see an example of global.asa in lesson 10.

What's Next:

We've seen in the last two lessons that Apartment Model Behavior is strictly forbidden in the Application Intrinsic Object. (It's not forbidden in the Session Object, but it is restricted.) So how do we store values (functions in particular) for reuse in many scripts? That is the subject of Lesson 13.


------------------------------- 13 -----------------------------------

nclude Files

Server Side Includes:

Experienced JavaScript programmers know that code reuse is good. Experienced JavaScript programmers also know that JavaScript functions are data types.

So, we should be able to store a JavaScript function inside a Session Variable or an Application Variable, right? Unfortunately, no. The way to reuse JavaScript functions across many pages is to use SSI: Server Side Includes.

<%@LANGUAGE="JavaScript"%>


ASP JavaScript Lessons(8-14)-speakitnow-ChinaUnix博客
  • 博客访问: 5547949
  • 博文数量: 915
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 5216
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-15 17:17
文章分类

全部博文(915)

文章存档

2011年(1)

2008年(134)

2007年(287)

2006年(493)

我的朋友
微信关注

IT168企业级官微



微信号:IT168qiye



系统架构师大会



微信号:SACC2013

订阅
热词专题
ASP JavaScript Lessons(8-14) 2006-12-31 14:48:22

分类: Java

-------------------------------- 8 -----------------------------------

The Request Object

Request Object:

Request has five (5) Collections, one (1) Property, and one (1) Method. You'll use the Collections far more than the property or the method.

Request Collections:

Below is a table of the Request Collections and descriptions of how they are used.

Request Collections
ClientCertificateRequest.ClientCertificate("Key[Field]")
Client security info for SSL encryption
CookiesRequest.Cookies("cookieName")
Holds cookie value stored on the client
FormRequest.Form("formName")
Holds value sent via HTML Form
QueryStringRequest.QueryString("keyName")
Name/Value pair appended to the end of the URL
ServerVariablesRequest.ServerVariables("variableName")
Hold values sent in the HTTP Headers

ClientCertificate:

Request.ClientCertificate is used with S.S.L. (Secure Sockets Layer). It is beyond the scope of this web site.

Cookies:

We will learn Request.Cookies and Response.Cookies together in Lesson 08. Please be patient.

Form:

Request.Form is probably the workhorse of the Request Collections. The first script is a repeat from Lesson 03.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

Type something into the text box and submit it.



How Much Money do you make each month?






Click Here to run script08.asp in a new window. It posts information to script08a.asp which is found below. In turn, script08a.asp posts information to script08b.asp which is also found below.

<%@LANGUAGE="JavaScript"%>
<%
var WebPageVariable = new String( Request.Form("WebPageVariable") )
WebPageVariable = WebPageVariable.toUpperCase();

var monthlySalary = new String( Request.Form("monthlySalary") )
monthlySalary = monthlySalary.toLowerCase();
%>

The Web Page Variable you typed is: <%=WebPageVariable%>

The monthly salary you listed is: <%=monthlySalary%>



Click the button to see Query Strings




We'll be using Request.Form when we "Post" an HTML form to the server. Notice that the NAME attribute in the HTML form corresponds to the "name" in Request.Form("name"). To be more specific, corresponds with Request.Form("WebPageVariable"). We already talked about the need for the new String( ) constructor back in Lesson 03.

QueryString:

We'll be using Request.QueryString when we use an HTML form to "Get" a page from the server. Request.QueryString() is very similar to Request.Form(). Take a look at script08b.asp which I printed below.

<%@LANGUAGE="JavaScript"%>
<%
var QueryVariable = new String( Request.QueryString("QueryVariable") )
%>

The QueryString Value is: <%=QueryVariable%>

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>
Click Here
for the link to script08b.asp?QueryVariable=<%=QueryVariable%>
<%
} //closing bracket for if statement.
%>

If you haven't already, Click Here to run script08.asp in a new window. Cycle through all the forms and links, and then come back.

You can use Request.QueryString in two different ways. You can either use an HTML form to "Get" a page from the server, which will generate a query string. Or you can manually build a query string and add it to the backside of a link. We'll dissect script08b.asp from top to bottom.

var QueryVariable = new String( Request.QueryString("QueryVariable") )

The line above in script08b.asp corresponds to the line below from script08a.asp


The NAME="someName" in the HTML form becomes the Request.QueryString("someName") on the next page.

About half way into script08b.asp are the lines I reprinted below.

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>

We've already converted Request.QueryString() into a JavaScript string at the top of the script. So, now we can do a string comparison.

If the QueryVariable hasn't already been set equal to "Lesson 08's new Query!" then we do that. Then we use the escape( ) method to convert white space and special characters into Unicode. (URL's should contain neither whitespace, nor most special characters.)

In lesson 14 we'll see a better way to encode URL's. When we study the Server Object, we'll see Server.URLEncode(). But for now, just know that escape() works.

You can have more than one QueryString on each page. If you lose count of your QueryStrings, then you use Request.QueryString.Count to tell you the number.

The Request Shortcut:

Request.Form() and Request.QueryString() share a shortcut. Request.Form("WebPageVariable") can be abbreviated as Request("WebPageVariable") and Request.QueryString("QueryVariable") can be abbreviated as Request("QueryVariable").

ServerVariables:

Server Variables represent the HTTP Headers sent to the server by the client. I won't demonstrate them all, because there are too many.

<%@LANGUAGE="JavaScript"%>










ALL_RAW<%=Request.ServerVariables("ALL_RAW")%>
REMOTE_ADDR<%=Request.ServerVariables("REMOTE_ADDR")%>
HTTP_USER_AGENT<%=Request.ServerVariables("HTTP_USER_AGENT")%>
URL<%=Request.ServerVariables("URL")%>


Click Here to run the script in a new window.

Demonstrated above are four (4) server variables. There are (give or take) about 50 server variables available. You can look up the full list of server variables for yourself on the internet.

Misc. Notes:

Request.BinaryRead() is the lone method and TotalBytes is the lone property. Request.BinaryRead(Request.TotalBytes) retrieves data from an HTML form using "POST." You must supply the TotalBytes as an argument. It stores the data into an array. BinaryRead cannot be used at the same time as Request.Form().

Next Stop, Cookies:

The only Request Collection I did not cover was Cookies. I want to cover Request.Cookies and Response.Cookies side by side. So we'll do that in Lesson 09.


-------------------------------- 9 -----------------------------------

ookies and Cookies

Response Cookies in General:

We'll start with the Response Cookies collection. I don't think it could be any easier. You simply put the name of the cookie in the argument. The corresponding value is a string. The only time it gets complicated is when you use keys (which I demonstrate below).

<%@LANGUAGE="JavaScript"%>
<%
var Tomorrow=new Date()
Tomorrow.setDate(Tomorrow.getDate() + 1)
myExpire = (Tomorrow.getMonth() + 1) + "/" + Tomorrow.getDate()
myExpire += "/" + Tomorrow.getFullYear()

Response.Cookies("firstCookie") = "I like cookies."
Response.Cookies("firstCookie").Expires=myExpire

Response.Cookies("secondCookie") = "ASP Cookies Are Easy."
Response.Cookies("secondCookie").Expires=myExpire

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."
Response.Cookies("thirdCookie").Expires=myExpire
%>


We're just setting <%=Response.Cookies.Count%> cookies.

Click Here to retrieve these cookies.

Click Here to run the script in a new window.

Setting a cookie with ASP is pretty simple. The format is Response.Cookies("name")="value". That "value" can be either a JavaScript string or an ASP native type such as Request.Form("userEmail").

Response Cookie Keys:

If on the first page of your ASP application Response.Cookies("myOnlyCookie") is set, and subsequently on page two of your application Response.Cookies("myOnlyCookie") is reassigned a second value, then only the second value will remain. The first value is lost in this circumstance.

The solution is to either use multiple cookies or to use multiple Keys in the SAME cookie.

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."

The Setting of one or more Keys is pretty simple. It follows this format: Response.Cookies("name")("key")="value". Again, the "value" can either be a JavaScript string or ASP native type. The advantage of using keys is that you can store multiple Key/Value pairs inside the very same cookie.

Request Cookies:

Generally you will find ASP cookie management to be far easier than Client Side JavaScript cookies. Down below is the script that retrieves the cookies.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
var firstCookie = Request.Cookies("firstCookie");
var secondCookie = Request.Cookies("secondCookie");
var thirdCookie2Keys = Request.Cookies("thirdCookie")("firstKey")
thirdCookie2Keys += " " + Request.Cookies("thirdCookie")("secondKey");
%>

There are <%=Request.Cookies.Count%> Cookies.

1) <%=firstCookie%>

2) <%=secondCookie%>

3) <%=thirdCookie2Keys%>

Click Here to see how we would sort cookies
if we didn't know their names.

Click Here to run the script in a new window.

Do I even need to explain "firstCookie" and "secondCookie"? It's so easy. However, I will have to have explain the retrieval of Keys in "thirdCookie".

We retrieve cookies in almost exactly the same way that we set them, and that goes for Keys as well. If you keep track of your Key names, then retrieving their values is pretty easy.

var thirdCookieFirstKey = Request.Cookies("thirdCookie")("firstKey")

Deleting Cookies:

To delete a cookie, give it an expiration date in the past. The following is not in our examples, but it would work.

var Yesterday=new Date()
Yesterday.setDate(Yesterday.getDate() - 1)
myExpire = (Yesterday.getMonth() + 1) + "/" + Yesterday.getDate()
myExpire += "/" + Yesterday.getFullYear()
Response.Cookies("firstCookie").Expires=myExpire

Cookie Crumbs:

What if you lose track of your cookie names? What if you lose your Keys? First of all, don't do that. But secondly, we have options.

We can use a VBScript Function with a for/each loop. We can use Javascript's new Enumerator( ) or we can use a pair of for Loops. We, however, cannot use JavaScript's for/in loop. This means we have to be creative.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
%>


<%
Response.Write("Let's use a VBScript function to ")
Response.Write("sort out the Cookies and Keys.

\r")
var longCookie = forEachCookie()
if (longCookie)
{
longCookie = longCookie.split("; ")
for (i=0;i<=longCookie.length-1;i++)
{
Response.Write(longCookie[ i ] + "
\r")
}
}
Response.Write("
\r")

Response.Write("Let's use new Enumerator( ) to ")
Response.Write("sort out the Cookies and Keys.

\r")
var myEnum = new Enumerator(Request.Cookies);
for (myEnum; !myEnum.atEnd() ; myEnum.moveNext() )
{
Response.Write(myEnum.item() + "=")
n=Request.Cookies(myEnum.item()).Count
if (n)
{
for (o=1;o<=n;o++)
{
Response.Write(Request.Cookies(myEnum.item())(o) + " ")
}
//Begin alternate method of using Enumerator()
Response.Write("
\rOR... ")
Response.Write(myEnum.item() + "=")
Response.Write(unescape(Request.Cookies(myEnum.item())))
//End alternate method
}
else
{
Response.Write(Request.Cookies(myEnum.item()))
}
Response.Write("
\r")
}
Response.Write("
\r")

Response.Write("Let's use a pair of JavaScript loops to ")
Response.Write("sort out the Cookies and Keys.

\r")
a=Request.Cookies.Count
for (b=1;b<=a;b++)
{
d = Request.Cookies(b).Count
if (d)
{
for (c=1;c<=d;c++)
{
Response.Write(Request.Cookies(b)(c) + " ")
}
Response.Write("
\r")
}
else
{
Response.Write(Request.Cookies(b) + "
\r")
}
}
%>

Click Here to run the script in a new window.

We do the same job three times. You decide for yourself which one you like best. In the first example you can plainly see from the script, I ask a VBScript function to find and break down all the cookies. I then output the data back to the waiting JavaScript variable.

var longCookie = forEachCookie()

What can I say? Don't lose track of your cookies and don't lose track of your Keys. Otherwise you might have to get a VBScript slim jim.

The new Enumerator() is okay. I use Enumerator two different ways; one way fails to capture the Key names, and the other way successfully captures the key names (but it needs unescape() to get the Key values to print normally).

In round three, I use a pair of for loops, but they're not as functional as for/in would be. (Notice the lack of Key names.)

Misc. Notes:

We didn't use new String( ) in this lesson. But remember, if you want to manipulate the cookie values inside JavaScript functions or methods, then you will need new String().

var firstCookie = new String(Request.Cookies("firstCookie") )
firstCookie = firstCookie.toUpperCase()

Also, if you were to use Client Side scripting to locate cookies, you would have noticed that there is an extra cookie. ASP keeps track of its sessions using a cookie.



------------------------------- 10 -----------------------------------

lobal ASA

Global.asa:

First of all, what is a global.asa? It's an optional script file that holds certain "global" information that you can access through the entire ASP appliciation. The global.asa is a plain text file saved with the .asa extension.

You should only have one global.asa and it should go in your top level directory.

Below is an example global.asa file. Don't try to understand the script just yet. We'll get to the specifics in the next two lessons.







List of Can Do's:

There are four things you can do with a global.asa.

1) Object Declarations
2) Application Events
3) Session Events
4) Library Reference.

I don't expect you understand any of that yet. Just remember, there are only a few things we can do with the global.asa. Let's move on to lesson 11.



------------------------------- 11 -----------------------------------

pplication Object

Overview:

The Application Object represents a collection of ASP pages. The Application object has zero (0) properties, two (2) collections, two (2) methods, and two (2) events.

Get Started:

Below are a couple scripts for lesson11.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>


Would you like to chose the official Application color?





No, click here.

Click Here to run script11.asp in a new window. Below is script11a.asp.

<%@LANGUAGE="JavaScript"%>

<%
Application.Lock()
var OfficialColor = new String( Request.Form("OfficialColor") )
if (OfficialColor=="red")
{
Application("OfficialColor") = "red"
}
if (OfficialColor=="white")
{
Application("OfficialColor") = "white"
}
if (OfficialColor=="blue")
{
Application("OfficialColor") = "blue"
}
if (OfficialColor=="undefined")
{
//Do nothing. Just leave the color alone.
}
Application.Unlock()
%>
">

The official application color is <%=Application("OfficialColor")%>.




Application Collections:

The two collections are Contents and StaticObjects. StaticObjects come in the form of the flag. That's done in the global.asa that we saw in Lesson 09. I'll demonstrate it again down below.

By contrast, the Contents collection is demonstrated above. It allows you to set and retrieve variables with Application scope. The format for setting an Application variable is Application.Contents("VariableName")="VariableValue". However, since Contents is the default Collection, we have a little shortcut for setting Application variables. The shortcut goes like this: Application("VariableName")="VariableValue".

Share the Variable:

One last thought on Application Variables. The application variable is shared by all visitors. Let's say that you and I are on the same ASP web site at the same time. If you set the background color to white in script11.asp, then I will see "white" as the official color if I go directly to script11a.asp. Application Variables are by no means the most efficient means of passing information from one user to another.

No Apartment Model:

You may notice that the example above seems to be inefficient. Why not just directly assign Application("OfficialColor") = Request.Form("OfficialColor")? Because we can't. By design, the newer (and updated) versions of Microsoft server software intentionally do not support Apartment Model Behavior.

Application Methods:

The two Application Methods are Lock() and Unlock(). Lock() blocks all other users from changing the Application variables. Unlock() releases control so that other users can change it. That's important on a larger site where multiple users may be trying to access the same page at the same time.

Application Events:

The two Application events are Application_OnStart() and Application_OnEnd(). These events are accessed in the global.asa. Let's repeat that script from lesson 09.







Misc. Items:

Application.Contents has two methods of its own. Application.Contents.Remove("VariableName") and Application.Contents.RemoveAll().

You'll notice there are also Session Events in the global.asa. We'll deal with those in Lesson 12. You'll also notice a call to the ADO Library. We'll talk about that when we get to databases.


------------------------------- 12 -----------------------------------

ession Object

Overview:

The Session Object is how you track a single user across many pages. It has four (4) properties, two (2) collections, one (1) method, and two (2) events.

Get Started:

In this series of examples we will create a password system. We will use the Session Object to track whether or not a user is authorized to view certain pages. Below are several scripts for lesson12. Look at them, play with, and then read the explanations that come further down the page.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

To play along with our password page, put in a user name and a password.


The correct user name is guest.

And the correct password is also guest.


User:

Pass:





Click Here to run script12.asp in a new window. Below is script12a.asp.

<%@LANGUAGE="JavaScript"%>
<%
var userName=new String(Request.Form("userName"))
var userPassword=new String(Request.Form("userPassword"))
if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}
else
{
Session("Authorized")=false
%>

You did not supply the correct Name & Password.

Click here to log in.

<%
} //end else statement
%>

We'll skip over script12b.asp entirely because it's almost exactly the same as script12c.asp. Down below is script12c.asp.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
%>

The second of two pages that are password protected.

Click Here to log out.

<%
} //end of else statement
%>

Above is script12c.asp, which is the second of two password-protected pages. Below is script12.asp, which is the logout page.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
var SessionID=Session.SessionID
Session.Abandon()
%>

You have sucessfully logged out.

This was session <%=SessionID%>.


Now try a link to one of the
pages you've already visited.


script12b.asp

script12c.asp

script12d.asp


<%
} //end of else statement
%>

A Quick Explanation:

After all that, the last thing you want to see is another grey box full of code. Sorry to do it one more time but, the keystone to this system is in script12a.asp. I've reprinted it down below.

if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}

Any page can now be turned into a password protected page with the following line: if (Session("Authorized")!=true). Session Variables are part of the Session Collections. Let's talk about them.

Session Collections:

The two Session Collections are Session.Contents and Session.StaticObjects. They parallel the Application.Contents and Application.StaticObjects.

Using Session.Contents("someVariable")="someValue" we can set Session Variables. These variables allow us to carry values from one page to the next. Since Contents is the default collection we can use a little shortcut. It goes like this: Session("someVariable")="someValue".

The shortcut is what you saw in the scripts above.

Session.Contents has two methods of its own. They are Session.Contents.Remove("variableName") and Session.Contents.RemoveAll().

We did not demonstrate StaticObjects in the scripts above. It comes in the form of the flag (set for Session scope).

No Sharing:

Remember how Application variables could be shared by all viewers on your ASP web site? That's not so with Session Variables. They are private; Session Variables are to be accessed only by one user.

Session.Abandon( ):

My bet is you could figure out Session.Abandon() without any explanation. However, let me just state for the record that Session.Abandon() ends the user's session and releases the Session Variables from memory.

Session Properties:

Let's briefly discuss two properties you are not likely to use. Session.CodePage lets you call for foreign character sets, like Chinese or Russian. Session.LCID is a location identifier. It determines the time zone and language for the server. Don't mess with it.

Now let's move on to something you might actually use from time to time. Session.SessionID is a read-only property generated by the server, and assigned to one specific user during one specific session. The SessionID follows the user from the beginning of the session until the end.

Session.Timeout is the number of minutes that a user can be idle before the Server ends the user's individual session and reclaims the memory that was allocated to Session Variables. (Session.Timeout is demonstrated in the global.asa in lesson 10.)

Session Events:

The two Session events are Session_OnStart() and Session_OnEnd(). These events are accessed in the global.asa. You can see an example of global.asa in lesson 10.

What's Next:

We've seen in the last two lessons that Apartment Model Behavior is strictly forbidden in the Application Intrinsic Object. (It's not forbidden in the Session Object, but it is restricted.) So how do we store values (functions in particular) for reuse in many scripts? That is the subject of Lesson 13.


------------------------------- 13 -----------------------------------

nclude Files

Server Side Includes:

Experienced JavaScript programmers know that code reuse is good. Experienced JavaScript programmers also know that JavaScript functions are data types.

So, we should be able to store a JavaScript function inside a Session Variable or an Application Variable, right? Unfortunately, no. The way to reuse JavaScript functions across many pages is to use SSI: Server Side Includes.

<%@LANGUAGE="JavaScript"%>


ASP JavaScript Lessons(8-14)-speakitnow-ChinaUnix博客
  • 博客访问: 5547950
  • 博文数量: 915
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 5216
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-15 17:17
文章分类

全部博文(915)

文章存档

2011年(1)

2008年(134)

2007年(287)

2006年(493)

我的朋友
微信关注

IT168企业级官微



微信号:IT168qiye



系统架构师大会



微信号:SACC2013

订阅
热词专题
ASP JavaScript Lessons(8-14) 2006-12-31 14:48:22

分类: Java

-------------------------------- 8 -----------------------------------

The Request Object

Request Object:

Request has five (5) Collections, one (1) Property, and one (1) Method. You'll use the Collections far more than the property or the method.

Request Collections:

Below is a table of the Request Collections and descriptions of how they are used.

Request Collections
ClientCertificateRequest.ClientCertificate("Key[Field]")
Client security info for SSL encryption
CookiesRequest.Cookies("cookieName")
Holds cookie value stored on the client
FormRequest.Form("formName")
Holds value sent via HTML Form
QueryStringRequest.QueryString("keyName")
Name/Value pair appended to the end of the URL
ServerVariablesRequest.ServerVariables("variableName")
Hold values sent in the HTTP Headers

ClientCertificate:

Request.ClientCertificate is used with S.S.L. (Secure Sockets Layer). It is beyond the scope of this web site.

Cookies:

We will learn Request.Cookies and Response.Cookies together in Lesson 08. Please be patient.

Form:

Request.Form is probably the workhorse of the Request Collections. The first script is a repeat from Lesson 03.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

Type something into the text box and submit it.



How Much Money do you make each month?






Click Here to run script08.asp in a new window. It posts information to script08a.asp which is found below. In turn, script08a.asp posts information to script08b.asp which is also found below.

<%@LANGUAGE="JavaScript"%>
<%
var WebPageVariable = new String( Request.Form("WebPageVariable") )
WebPageVariable = WebPageVariable.toUpperCase();

var monthlySalary = new String( Request.Form("monthlySalary") )
monthlySalary = monthlySalary.toLowerCase();
%>

The Web Page Variable you typed is: <%=WebPageVariable%>

The monthly salary you listed is: <%=monthlySalary%>



Click the button to see Query Strings




We'll be using Request.Form when we "Post" an HTML form to the server. Notice that the NAME attribute in the HTML form corresponds to the "name" in Request.Form("name"). To be more specific, corresponds with Request.Form("WebPageVariable"). We already talked about the need for the new String( ) constructor back in Lesson 03.

QueryString:

We'll be using Request.QueryString when we use an HTML form to "Get" a page from the server. Request.QueryString() is very similar to Request.Form(). Take a look at script08b.asp which I printed below.

<%@LANGUAGE="JavaScript"%>
<%
var QueryVariable = new String( Request.QueryString("QueryVariable") )
%>

The QueryString Value is: <%=QueryVariable%>

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>
Click Here
for the link to script08b.asp?QueryVariable=<%=QueryVariable%>
<%
} //closing bracket for if statement.
%>

If you haven't already, Click Here to run script08.asp in a new window. Cycle through all the forms and links, and then come back.

You can use Request.QueryString in two different ways. You can either use an HTML form to "Get" a page from the server, which will generate a query string. Or you can manually build a query string and add it to the backside of a link. We'll dissect script08b.asp from top to bottom.

var QueryVariable = new String( Request.QueryString("QueryVariable") )

The line above in script08b.asp corresponds to the line below from script08a.asp


The NAME="someName" in the HTML form becomes the Request.QueryString("someName") on the next page.

About half way into script08b.asp are the lines I reprinted below.

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>

We've already converted Request.QueryString() into a JavaScript string at the top of the script. So, now we can do a string comparison.

If the QueryVariable hasn't already been set equal to "Lesson 08's new Query!" then we do that. Then we use the escape( ) method to convert white space and special characters into Unicode. (URL's should contain neither whitespace, nor most special characters.)

In lesson 14 we'll see a better way to encode URL's. When we study the Server Object, we'll see Server.URLEncode(). But for now, just know that escape() works.

You can have more than one QueryString on each page. If you lose count of your QueryStrings, then you use Request.QueryString.Count to tell you the number.

The Request Shortcut:

Request.Form() and Request.QueryString() share a shortcut. Request.Form("WebPageVariable") can be abbreviated as Request("WebPageVariable") and Request.QueryString("QueryVariable") can be abbreviated as Request("QueryVariable").

ServerVariables:

Server Variables represent the HTTP Headers sent to the server by the client. I won't demonstrate them all, because there are too many.

<%@LANGUAGE="JavaScript"%>










ALL_RAW<%=Request.ServerVariables("ALL_RAW")%>
REMOTE_ADDR<%=Request.ServerVariables("REMOTE_ADDR")%>
HTTP_USER_AGENT<%=Request.ServerVariables("HTTP_USER_AGENT")%>
URL<%=Request.ServerVariables("URL")%>


Click Here to run the script in a new window.

Demonstrated above are four (4) server variables. There are (give or take) about 50 server variables available. You can look up the full list of server variables for yourself on the internet.

Misc. Notes:

Request.BinaryRead() is the lone method and TotalBytes is the lone property. Request.BinaryRead(Request.TotalBytes) retrieves data from an HTML form using "POST." You must supply the TotalBytes as an argument. It stores the data into an array. BinaryRead cannot be used at the same time as Request.Form().

Next Stop, Cookies:

The only Request Collection I did not cover was Cookies. I want to cover Request.Cookies and Response.Cookies side by side. So we'll do that in Lesson 09.


-------------------------------- 9 -----------------------------------

ookies and Cookies

Response Cookies in General:

We'll start with the Response Cookies collection. I don't think it could be any easier. You simply put the name of the cookie in the argument. The corresponding value is a string. The only time it gets complicated is when you use keys (which I demonstrate below).

<%@LANGUAGE="JavaScript"%>
<%
var Tomorrow=new Date()
Tomorrow.setDate(Tomorrow.getDate() + 1)
myExpire = (Tomorrow.getMonth() + 1) + "/" + Tomorrow.getDate()
myExpire += "/" + Tomorrow.getFullYear()

Response.Cookies("firstCookie") = "I like cookies."
Response.Cookies("firstCookie").Expires=myExpire

Response.Cookies("secondCookie") = "ASP Cookies Are Easy."
Response.Cookies("secondCookie").Expires=myExpire

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."
Response.Cookies("thirdCookie").Expires=myExpire
%>


We're just setting <%=Response.Cookies.Count%> cookies.

Click Here to retrieve these cookies.

Click Here to run the script in a new window.

Setting a cookie with ASP is pretty simple. The format is Response.Cookies("name")="value". That "value" can be either a JavaScript string or an ASP native type such as Request.Form("userEmail").

Response Cookie Keys:

If on the first page of your ASP application Response.Cookies("myOnlyCookie") is set, and subsequently on page two of your application Response.Cookies("myOnlyCookie") is reassigned a second value, then only the second value will remain. The first value is lost in this circumstance.

The solution is to either use multiple cookies or to use multiple Keys in the SAME cookie.

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."

The Setting of one or more Keys is pretty simple. It follows this format: Response.Cookies("name")("key")="value". Again, the "value" can either be a JavaScript string or ASP native type. The advantage of using keys is that you can store multiple Key/Value pairs inside the very same cookie.

Request Cookies:

Generally you will find ASP cookie management to be far easier than Client Side JavaScript cookies. Down below is the script that retrieves the cookies.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
var firstCookie = Request.Cookies("firstCookie");
var secondCookie = Request.Cookies("secondCookie");
var thirdCookie2Keys = Request.Cookies("thirdCookie")("firstKey")
thirdCookie2Keys += " " + Request.Cookies("thirdCookie")("secondKey");
%>

There are <%=Request.Cookies.Count%> Cookies.

1) <%=firstCookie%>

2) <%=secondCookie%>

3) <%=thirdCookie2Keys%>

Click Here to see how we would sort cookies
if we didn't know their names.

Click Here to run the script in a new window.

Do I even need to explain "firstCookie" and "secondCookie"? It's so easy. However, I will have to have explain the retrieval of Keys in "thirdCookie".

We retrieve cookies in almost exactly the same way that we set them, and that goes for Keys as well. If you keep track of your Key names, then retrieving their values is pretty easy.

var thirdCookieFirstKey = Request.Cookies("thirdCookie")("firstKey")

Deleting Cookies:

To delete a cookie, give it an expiration date in the past. The following is not in our examples, but it would work.

var Yesterday=new Date()
Yesterday.setDate(Yesterday.getDate() - 1)
myExpire = (Yesterday.getMonth() + 1) + "/" + Yesterday.getDate()
myExpire += "/" + Yesterday.getFullYear()
Response.Cookies("firstCookie").Expires=myExpire

Cookie Crumbs:

What if you lose track of your cookie names? What if you lose your Keys? First of all, don't do that. But secondly, we have options.

We can use a VBScript Function with a for/each loop. We can use Javascript's new Enumerator( ) or we can use a pair of for Loops. We, however, cannot use JavaScript's for/in loop. This means we have to be creative.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
%>


<%
Response.Write("Let's use a VBScript function to ")
Response.Write("sort out the Cookies and Keys.

\r")
var longCookie = forEachCookie()
if (longCookie)
{
longCookie = longCookie.split("; ")
for (i=0;i<=longCookie.length-1;i++)
{
Response.Write(longCookie[ i ] + "
\r")
}
}
Response.Write("
\r")

Response.Write("Let's use new Enumerator( ) to ")
Response.Write("sort out the Cookies and Keys.

\r")
var myEnum = new Enumerator(Request.Cookies);
for (myEnum; !myEnum.atEnd() ; myEnum.moveNext() )
{
Response.Write(myEnum.item() + "=")
n=Request.Cookies(myEnum.item()).Count
if (n)
{
for (o=1;o<=n;o++)
{
Response.Write(Request.Cookies(myEnum.item())(o) + " ")
}
//Begin alternate method of using Enumerator()
Response.Write("
\rOR... ")
Response.Write(myEnum.item() + "=")
Response.Write(unescape(Request.Cookies(myEnum.item())))
//End alternate method
}
else
{
Response.Write(Request.Cookies(myEnum.item()))
}
Response.Write("
\r")
}
Response.Write("
\r")

Response.Write("Let's use a pair of JavaScript loops to ")
Response.Write("sort out the Cookies and Keys.

\r")
a=Request.Cookies.Count
for (b=1;b<=a;b++)
{
d = Request.Cookies(b).Count
if (d)
{
for (c=1;c<=d;c++)
{
Response.Write(Request.Cookies(b)(c) + " ")
}
Response.Write("
\r")
}
else
{
Response.Write(Request.Cookies(b) + "
\r")
}
}
%>

Click Here to run the script in a new window.

We do the same job three times. You decide for yourself which one you like best. In the first example you can plainly see from the script, I ask a VBScript function to find and break down all the cookies. I then output the data back to the waiting JavaScript variable.

var longCookie = forEachCookie()

What can I say? Don't lose track of your cookies and don't lose track of your Keys. Otherwise you might have to get a VBScript slim jim.

The new Enumerator() is okay. I use Enumerator two different ways; one way fails to capture the Key names, and the other way successfully captures the key names (but it needs unescape() to get the Key values to print normally).

In round three, I use a pair of for loops, but they're not as functional as for/in would be. (Notice the lack of Key names.)

Misc. Notes:

We didn't use new String( ) in this lesson. But remember, if you want to manipulate the cookie values inside JavaScript functions or methods, then you will need new String().

var firstCookie = new String(Request.Cookies("firstCookie") )
firstCookie = firstCookie.toUpperCase()

Also, if you were to use Client Side scripting to locate cookies, you would have noticed that there is an extra cookie. ASP keeps track of its sessions using a cookie.



------------------------------- 10 -----------------------------------

lobal ASA

Global.asa:

First of all, what is a global.asa? It's an optional script file that holds certain "global" information that you can access through the entire ASP appliciation. The global.asa is a plain text file saved with the .asa extension.

You should only have one global.asa and it should go in your top level directory.

Below is an example global.asa file. Don't try to understand the script just yet. We'll get to the specifics in the next two lessons.







List of Can Do's:

There are four things you can do with a global.asa.

1) Object Declarations
2) Application Events
3) Session Events
4) Library Reference.

I don't expect you understand any of that yet. Just remember, there are only a few things we can do with the global.asa. Let's move on to lesson 11.



------------------------------- 11 -----------------------------------

pplication Object

Overview:

The Application Object represents a collection of ASP pages. The Application object has zero (0) properties, two (2) collections, two (2) methods, and two (2) events.

Get Started:

Below are a couple scripts for lesson11.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>


Would you like to chose the official Application color?





No, click here.

Click Here to run script11.asp in a new window. Below is script11a.asp.

<%@LANGUAGE="JavaScript"%>

<%
Application.Lock()
var OfficialColor = new String( Request.Form("OfficialColor") )
if (OfficialColor=="red")
{
Application("OfficialColor") = "red"
}
if (OfficialColor=="white")
{
Application("OfficialColor") = "white"
}
if (OfficialColor=="blue")
{
Application("OfficialColor") = "blue"
}
if (OfficialColor=="undefined")
{
//Do nothing. Just leave the color alone.
}
Application.Unlock()
%>
">

The official application color is <%=Application("OfficialColor")%>.




Application Collections:

The two collections are Contents and StaticObjects. StaticObjects come in the form of the flag. That's done in the global.asa that we saw in Lesson 09. I'll demonstrate it again down below.

By contrast, the Contents collection is demonstrated above. It allows you to set and retrieve variables with Application scope. The format for setting an Application variable is Application.Contents("VariableName")="VariableValue". However, since Contents is the default Collection, we have a little shortcut for setting Application variables. The shortcut goes like this: Application("VariableName")="VariableValue".

Share the Variable:

One last thought on Application Variables. The application variable is shared by all visitors. Let's say that you and I are on the same ASP web site at the same time. If you set the background color to white in script11.asp, then I will see "white" as the official color if I go directly to script11a.asp. Application Variables are by no means the most efficient means of passing information from one user to another.

No Apartment Model:

You may notice that the example above seems to be inefficient. Why not just directly assign Application("OfficialColor") = Request.Form("OfficialColor")? Because we can't. By design, the newer (and updated) versions of Microsoft server software intentionally do not support Apartment Model Behavior.

Application Methods:

The two Application Methods are Lock() and Unlock(). Lock() blocks all other users from changing the Application variables. Unlock() releases control so that other users can change it. That's important on a larger site where multiple users may be trying to access the same page at the same time.

Application Events:

The two Application events are Application_OnStart() and Application_OnEnd(). These events are accessed in the global.asa. Let's repeat that script from lesson 09.







Misc. Items:

Application.Contents has two methods of its own. Application.Contents.Remove("VariableName") and Application.Contents.RemoveAll().

You'll notice there are also Session Events in the global.asa. We'll deal with those in Lesson 12. You'll also notice a call to the ADO Library. We'll talk about that when we get to databases.


------------------------------- 12 -----------------------------------

ession Object

Overview:

The Session Object is how you track a single user across many pages. It has four (4) properties, two (2) collections, one (1) method, and two (2) events.

Get Started:

In this series of examples we will create a password system. We will use the Session Object to track whether or not a user is authorized to view certain pages. Below are several scripts for lesson12. Look at them, play with, and then read the explanations that come further down the page.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

To play along with our password page, put in a user name and a password.


The correct user name is guest.

And the correct password is also guest.


User:

Pass:





Click Here to run script12.asp in a new window. Below is script12a.asp.

<%@LANGUAGE="JavaScript"%>
<%
var userName=new String(Request.Form("userName"))
var userPassword=new String(Request.Form("userPassword"))
if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}
else
{
Session("Authorized")=false
%>

You did not supply the correct Name & Password.

Click here to log in.

<%
} //end else statement
%>

We'll skip over script12b.asp entirely because it's almost exactly the same as script12c.asp. Down below is script12c.asp.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
%>

The second of two pages that are password protected.

Click Here to log out.

<%
} //end of else statement
%>

Above is script12c.asp, which is the second of two password-protected pages. Below is script12.asp, which is the logout page.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
var SessionID=Session.SessionID
Session.Abandon()
%>

You have sucessfully logged out.

This was session <%=SessionID%>.


Now try a link to one of the
pages you've already visited.


script12b.asp

script12c.asp

script12d.asp


<%
} //end of else statement
%>

A Quick Explanation:

After all that, the last thing you want to see is another grey box full of code. Sorry to do it one more time but, the keystone to this system is in script12a.asp. I've reprinted it down below.

if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}

Any page can now be turned into a password protected page with the following line: if (Session("Authorized")!=true). Session Variables are part of the Session Collections. Let's talk about them.

Session Collections:

The two Session Collections are Session.Contents and Session.StaticObjects. They parallel the Application.Contents and Application.StaticObjects.

Using Session.Contents("someVariable")="someValue" we can set Session Variables. These variables allow us to carry values from one page to the next. Since Contents is the default collection we can use a little shortcut. It goes like this: Session("someVariable")="someValue".

The shortcut is what you saw in the scripts above.

Session.Contents has two methods of its own. They are Session.Contents.Remove("variableName") and Session.Contents.RemoveAll().

We did not demonstrate StaticObjects in the scripts above. It comes in the form of the flag (set for Session scope).

No Sharing:

Remember how Application variables could be shared by all viewers on your ASP web site? That's not so with Session Variables. They are private; Session Variables are to be accessed only by one user.

Session.Abandon( ):

My bet is you could figure out Session.Abandon() without any explanation. However, let me just state for the record that Session.Abandon() ends the user's session and releases the Session Variables from memory.

Session Properties:

Let's briefly discuss two properties you are not likely to use. Session.CodePage lets you call for foreign character sets, like Chinese or Russian. Session.LCID is a location identifier. It determines the time zone and language for the server. Don't mess with it.

Now let's move on to something you might actually use from time to time. Session.SessionID is a read-only property generated by the server, and assigned to one specific user during one specific session. The SessionID follows the user from the beginning of the session until the end.

Session.Timeout is the number of minutes that a user can be idle before the Server ends the user's individual session and reclaims the memory that was allocated to Session Variables. (Session.Timeout is demonstrated in the global.asa in lesson 10.)

Session Events:

The two Session events are Session_OnStart() and Session_OnEnd(). These events are accessed in the global.asa. You can see an example of global.asa in lesson 10.

What's Next:

We've seen in the last two lessons that Apartment Model Behavior is strictly forbidden in the Application Intrinsic Object. (It's not forbidden in the Session Object, but it is restricted.) So how do we store values (functions in particular) for reuse in many scripts? That is the subject of Lesson 13.


------------------------------- 13 -----------------------------------

nclude Files

Server Side Includes:

Experienced JavaScript programmers know that code reuse is good. Experienced JavaScript programmers also know that JavaScript functions are data types.

So, we should be able to store a JavaScript function inside a Session Variable or an Application Variable, right? Unfortunately, no. The way to reuse JavaScript functions across many pages is to use SSI: Server Side Includes.

<%@LANGUAGE="JavaScript"%>


ASP JavaScript Lessons(8-14)-speakitnow-ChinaUnix博客
  • 博客访问: 5547951
  • 博文数量: 915
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 5216
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-15 17:17
文章分类

全部博文(915)

文章存档

2011年(1)

2008年(134)

2007年(287)

2006年(493)

我的朋友
微信关注

IT168企业级官微



微信号:IT168qiye



系统架构师大会



微信号:SACC2013

订阅
热词专题
ASP JavaScript Lessons(8-14) 2006-12-31 14:48:22

分类: Java

-------------------------------- 8 -----------------------------------

The Request Object

Request Object:

Request has five (5) Collections, one (1) Property, and one (1) Method. You'll use the Collections far more than the property or the method.

Request Collections:

Below is a table of the Request Collections and descriptions of how they are used.

Request Collections
ClientCertificateRequest.ClientCertificate("Key[Field]")
Client security info for SSL encryption
CookiesRequest.Cookies("cookieName")
Holds cookie value stored on the client
FormRequest.Form("formName")
Holds value sent via HTML Form
QueryStringRequest.QueryString("keyName")
Name/Value pair appended to the end of the URL
ServerVariablesRequest.ServerVariables("variableName")
Hold values sent in the HTTP Headers

ClientCertificate:

Request.ClientCertificate is used with S.S.L. (Secure Sockets Layer). It is beyond the scope of this web site.

Cookies:

We will learn Request.Cookies and Response.Cookies together in Lesson 08. Please be patient.

Form:

Request.Form is probably the workhorse of the Request Collections. The first script is a repeat from Lesson 03.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

Type something into the text box and submit it.



How Much Money do you make each month?






Click Here to run script08.asp in a new window. It posts information to script08a.asp which is found below. In turn, script08a.asp posts information to script08b.asp which is also found below.

<%@LANGUAGE="JavaScript"%>
<%
var WebPageVariable = new String( Request.Form("WebPageVariable") )
WebPageVariable = WebPageVariable.toUpperCase();

var monthlySalary = new String( Request.Form("monthlySalary") )
monthlySalary = monthlySalary.toLowerCase();
%>

The Web Page Variable you typed is: <%=WebPageVariable%>

The monthly salary you listed is: <%=monthlySalary%>



Click the button to see Query Strings




We'll be using Request.Form when we "Post" an HTML form to the server. Notice that the NAME attribute in the HTML form corresponds to the "name" in Request.Form("name"). To be more specific, corresponds with Request.Form("WebPageVariable"). We already talked about the need for the new String( ) constructor back in Lesson 03.

QueryString:

We'll be using Request.QueryString when we use an HTML form to "Get" a page from the server. Request.QueryString() is very similar to Request.Form(). Take a look at script08b.asp which I printed below.

<%@LANGUAGE="JavaScript"%>
<%
var QueryVariable = new String( Request.QueryString("QueryVariable") )
%>

The QueryString Value is: <%=QueryVariable%>

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>
Click Here
for the link to script08b.asp?QueryVariable=<%=QueryVariable%>
<%
} //closing bracket for if statement.
%>

If you haven't already, Click Here to run script08.asp in a new window. Cycle through all the forms and links, and then come back.

You can use Request.QueryString in two different ways. You can either use an HTML form to "Get" a page from the server, which will generate a query string. Or you can manually build a query string and add it to the backside of a link. We'll dissect script08b.asp from top to bottom.

var QueryVariable = new String( Request.QueryString("QueryVariable") )

The line above in script08b.asp corresponds to the line below from script08a.asp


The NAME="someName" in the HTML form becomes the Request.QueryString("someName") on the next page.

About half way into script08b.asp are the lines I reprinted below.

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>

We've already converted Request.QueryString() into a JavaScript string at the top of the script. So, now we can do a string comparison.

If the QueryVariable hasn't already been set equal to "Lesson 08's new Query!" then we do that. Then we use the escape( ) method to convert white space and special characters into Unicode. (URL's should contain neither whitespace, nor most special characters.)

In lesson 14 we'll see a better way to encode URL's. When we study the Server Object, we'll see Server.URLEncode(). But for now, just know that escape() works.

You can have more than one QueryString on each page. If you lose count of your QueryStrings, then you use Request.QueryString.Count to tell you the number.

The Request Shortcut:

Request.Form() and Request.QueryString() share a shortcut. Request.Form("WebPageVariable") can be abbreviated as Request("WebPageVariable") and Request.QueryString("QueryVariable") can be abbreviated as Request("QueryVariable").

ServerVariables:

Server Variables represent the HTTP Headers sent to the server by the client. I won't demonstrate them all, because there are too many.

<%@LANGUAGE="JavaScript"%>










ALL_RAW<%=Request.ServerVariables("ALL_RAW")%>
REMOTE_ADDR<%=Request.ServerVariables("REMOTE_ADDR")%>
HTTP_USER_AGENT<%=Request.ServerVariables("HTTP_USER_AGENT")%>
URL<%=Request.ServerVariables("URL")%>


Click Here to run the script in a new window.

Demonstrated above are four (4) server variables. There are (give or take) about 50 server variables available. You can look up the full list of server variables for yourself on the internet.

Misc. Notes:

Request.BinaryRead() is the lone method and TotalBytes is the lone property. Request.BinaryRead(Request.TotalBytes) retrieves data from an HTML form using "POST." You must supply the TotalBytes as an argument. It stores the data into an array. BinaryRead cannot be used at the same time as Request.Form().

Next Stop, Cookies:

The only Request Collection I did not cover was Cookies. I want to cover Request.Cookies and Response.Cookies side by side. So we'll do that in Lesson 09.


-------------------------------- 9 -----------------------------------

ookies and Cookies

Response Cookies in General:

We'll start with the Response Cookies collection. I don't think it could be any easier. You simply put the name of the cookie in the argument. The corresponding value is a string. The only time it gets complicated is when you use keys (which I demonstrate below).

<%@LANGUAGE="JavaScript"%>
<%
var Tomorrow=new Date()
Tomorrow.setDate(Tomorrow.getDate() + 1)
myExpire = (Tomorrow.getMonth() + 1) + "/" + Tomorrow.getDate()
myExpire += "/" + Tomorrow.getFullYear()

Response.Cookies("firstCookie") = "I like cookies."
Response.Cookies("firstCookie").Expires=myExpire

Response.Cookies("secondCookie") = "ASP Cookies Are Easy."
Response.Cookies("secondCookie").Expires=myExpire

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."
Response.Cookies("thirdCookie").Expires=myExpire
%>


We're just setting <%=Response.Cookies.Count%> cookies.

Click Here to retrieve these cookies.

Click Here to run the script in a new window.

Setting a cookie with ASP is pretty simple. The format is Response.Cookies("name")="value". That "value" can be either a JavaScript string or an ASP native type such as Request.Form("userEmail").

Response Cookie Keys:

If on the first page of your ASP application Response.Cookies("myOnlyCookie") is set, and subsequently on page two of your application Response.Cookies("myOnlyCookie") is reassigned a second value, then only the second value will remain. The first value is lost in this circumstance.

The solution is to either use multiple cookies or to use multiple Keys in the SAME cookie.

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."

The Setting of one or more Keys is pretty simple. It follows this format: Response.Cookies("name")("key")="value". Again, the "value" can either be a JavaScript string or ASP native type. The advantage of using keys is that you can store multiple Key/Value pairs inside the very same cookie.

Request Cookies:

Generally you will find ASP cookie management to be far easier than Client Side JavaScript cookies. Down below is the script that retrieves the cookies.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
var firstCookie = Request.Cookies("firstCookie");
var secondCookie = Request.Cookies("secondCookie");
var thirdCookie2Keys = Request.Cookies("thirdCookie")("firstKey")
thirdCookie2Keys += " " + Request.Cookies("thirdCookie")("secondKey");
%>

There are <%=Request.Cookies.Count%> Cookies.

1) <%=firstCookie%>

2) <%=secondCookie%>

3) <%=thirdCookie2Keys%>

Click Here to see how we would sort cookies
if we didn't know their names.

Click Here to run the script in a new window.

Do I even need to explain "firstCookie" and "secondCookie"? It's so easy. However, I will have to have explain the retrieval of Keys in "thirdCookie".

We retrieve cookies in almost exactly the same way that we set them, and that goes for Keys as well. If you keep track of your Key names, then retrieving their values is pretty easy.

var thirdCookieFirstKey = Request.Cookies("thirdCookie")("firstKey")

Deleting Cookies:

To delete a cookie, give it an expiration date in the past. The following is not in our examples, but it would work.

var Yesterday=new Date()
Yesterday.setDate(Yesterday.getDate() - 1)
myExpire = (Yesterday.getMonth() + 1) + "/" + Yesterday.getDate()
myExpire += "/" + Yesterday.getFullYear()
Response.Cookies("firstCookie").Expires=myExpire

Cookie Crumbs:

What if you lose track of your cookie names? What if you lose your Keys? First of all, don't do that. But secondly, we have options.

We can use a VBScript Function with a for/each loop. We can use Javascript's new Enumerator( ) or we can use a pair of for Loops. We, however, cannot use JavaScript's for/in loop. This means we have to be creative.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
%>


<%
Response.Write("Let's use a VBScript function to ")
Response.Write("sort out the Cookies and Keys.

\r")
var longCookie = forEachCookie()
if (longCookie)
{
longCookie = longCookie.split("; ")
for (i=0;i<=longCookie.length-1;i++)
{
Response.Write(longCookie[ i ] + "
\r")
}
}
Response.Write("
\r")

Response.Write("Let's use new Enumerator( ) to ")
Response.Write("sort out the Cookies and Keys.

\r")
var myEnum = new Enumerator(Request.Cookies);
for (myEnum; !myEnum.atEnd() ; myEnum.moveNext() )
{
Response.Write(myEnum.item() + "=")
n=Request.Cookies(myEnum.item()).Count
if (n)
{
for (o=1;o<=n;o++)
{
Response.Write(Request.Cookies(myEnum.item())(o) + " ")
}
//Begin alternate method of using Enumerator()
Response.Write("
\rOR... ")
Response.Write(myEnum.item() + "=")
Response.Write(unescape(Request.Cookies(myEnum.item())))
//End alternate method
}
else
{
Response.Write(Request.Cookies(myEnum.item()))
}
Response.Write("
\r")
}
Response.Write("
\r")

Response.Write("Let's use a pair of JavaScript loops to ")
Response.Write("sort out the Cookies and Keys.

\r")
a=Request.Cookies.Count
for (b=1;b<=a;b++)
{
d = Request.Cookies(b).Count
if (d)
{
for (c=1;c<=d;c++)
{
Response.Write(Request.Cookies(b)(c) + " ")
}
Response.Write("
\r")
}
else
{
Response.Write(Request.Cookies(b) + "
\r")
}
}
%>

Click Here to run the script in a new window.

We do the same job three times. You decide for yourself which one you like best. In the first example you can plainly see from the script, I ask a VBScript function to find and break down all the cookies. I then output the data back to the waiting JavaScript variable.

var longCookie = forEachCookie()

What can I say? Don't lose track of your cookies and don't lose track of your Keys. Otherwise you might have to get a VBScript slim jim.

The new Enumerator() is okay. I use Enumerator two different ways; one way fails to capture the Key names, and the other way successfully captures the key names (but it needs unescape() to get the Key values to print normally).

In round three, I use a pair of for loops, but they're not as functional as for/in would be. (Notice the lack of Key names.)

Misc. Notes:

We didn't use new String( ) in this lesson. But remember, if you want to manipulate the cookie values inside JavaScript functions or methods, then you will need new String().

var firstCookie = new String(Request.Cookies("firstCookie") )
firstCookie = firstCookie.toUpperCase()

Also, if you were to use Client Side scripting to locate cookies, you would have noticed that there is an extra cookie. ASP keeps track of its sessions using a cookie.



------------------------------- 10 -----------------------------------

lobal ASA

Global.asa:

First of all, what is a global.asa? It's an optional script file that holds certain "global" information that you can access through the entire ASP appliciation. The global.asa is a plain text file saved with the .asa extension.

You should only have one global.asa and it should go in your top level directory.

Below is an example global.asa file. Don't try to understand the script just yet. We'll get to the specifics in the next two lessons.







List of Can Do's:

There are four things you can do with a global.asa.

1) Object Declarations
2) Application Events
3) Session Events
4) Library Reference.

I don't expect you understand any of that yet. Just remember, there are only a few things we can do with the global.asa. Let's move on to lesson 11.



------------------------------- 11 -----------------------------------

pplication Object

Overview:

The Application Object represents a collection of ASP pages. The Application object has zero (0) properties, two (2) collections, two (2) methods, and two (2) events.

Get Started:

Below are a couple scripts for lesson11.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>


Would you like to chose the official Application color?





No, click here.

Click Here to run script11.asp in a new window. Below is script11a.asp.

<%@LANGUAGE="JavaScript"%>

<%
Application.Lock()
var OfficialColor = new String( Request.Form("OfficialColor") )
if (OfficialColor=="red")
{
Application("OfficialColor") = "red"
}
if (OfficialColor=="white")
{
Application("OfficialColor") = "white"
}
if (OfficialColor=="blue")
{
Application("OfficialColor") = "blue"
}
if (OfficialColor=="undefined")
{
//Do nothing. Just leave the color alone.
}
Application.Unlock()
%>
">

The official application color is <%=Application("OfficialColor")%>.




Application Collections:

The two collections are Contents and StaticObjects. StaticObjects come in the form of the flag. That's done in the global.asa that we saw in Lesson 09. I'll demonstrate it again down below.

By contrast, the Contents collection is demonstrated above. It allows you to set and retrieve variables with Application scope. The format for setting an Application variable is Application.Contents("VariableName")="VariableValue". However, since Contents is the default Collection, we have a little shortcut for setting Application variables. The shortcut goes like this: Application("VariableName")="VariableValue".

Share the Variable:

One last thought on Application Variables. The application variable is shared by all visitors. Let's say that you and I are on the same ASP web site at the same time. If you set the background color to white in script11.asp, then I will see "white" as the official color if I go directly to script11a.asp. Application Variables are by no means the most efficient means of passing information from one user to another.

No Apartment Model:

You may notice that the example above seems to be inefficient. Why not just directly assign Application("OfficialColor") = Request.Form("OfficialColor")? Because we can't. By design, the newer (and updated) versions of Microsoft server software intentionally do not support Apartment Model Behavior.

Application Methods:

The two Application Methods are Lock() and Unlock(). Lock() blocks all other users from changing the Application variables. Unlock() releases control so that other users can change it. That's important on a larger site where multiple users may be trying to access the same page at the same time.

Application Events:

The two Application events are Application_OnStart() and Application_OnEnd(). These events are accessed in the global.asa. Let's repeat that script from lesson 09.







Misc. Items:

Application.Contents has two methods of its own. Application.Contents.Remove("VariableName") and Application.Contents.RemoveAll().

You'll notice there are also Session Events in the global.asa. We'll deal with those in Lesson 12. You'll also notice a call to the ADO Library. We'll talk about that when we get to databases.


------------------------------- 12 -----------------------------------

ession Object

Overview:

The Session Object is how you track a single user across many pages. It has four (4) properties, two (2) collections, one (1) method, and two (2) events.

Get Started:

In this series of examples we will create a password system. We will use the Session Object to track whether or not a user is authorized to view certain pages. Below are several scripts for lesson12. Look at them, play with, and then read the explanations that come further down the page.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

To play along with our password page, put in a user name and a password.


The correct user name is guest.

And the correct password is also guest.


User:

Pass:





Click Here to run script12.asp in a new window. Below is script12a.asp.

<%@LANGUAGE="JavaScript"%>
<%
var userName=new String(Request.Form("userName"))
var userPassword=new String(Request.Form("userPassword"))
if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}
else
{
Session("Authorized")=false
%>

You did not supply the correct Name & Password.

Click here to log in.

<%
} //end else statement
%>

We'll skip over script12b.asp entirely because it's almost exactly the same as script12c.asp. Down below is script12c.asp.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
%>

The second of two pages that are password protected.

Click Here to log out.

<%
} //end of else statement
%>

Above is script12c.asp, which is the second of two password-protected pages. Below is script12.asp, which is the logout page.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
var SessionID=Session.SessionID
Session.Abandon()
%>

You have sucessfully logged out.

This was session <%=SessionID%>.


Now try a link to one of the
pages you've already visited.


script12b.asp

script12c.asp

script12d.asp


<%
} //end of else statement
%>

A Quick Explanation:

After all that, the last thing you want to see is another grey box full of code. Sorry to do it one more time but, the keystone to this system is in script12a.asp. I've reprinted it down below.

if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}

Any page can now be turned into a password protected page with the following line: if (Session("Authorized")!=true). Session Variables are part of the Session Collections. Let's talk about them.

Session Collections:

The two Session Collections are Session.Contents and Session.StaticObjects. They parallel the Application.Contents and Application.StaticObjects.

Using Session.Contents("someVariable")="someValue" we can set Session Variables. These variables allow us to carry values from one page to the next. Since Contents is the default collection we can use a little shortcut. It goes like this: Session("someVariable")="someValue".

The shortcut is what you saw in the scripts above.

Session.Contents has two methods of its own. They are Session.Contents.Remove("variableName") and Session.Contents.RemoveAll().

We did not demonstrate StaticObjects in the scripts above. It comes in the form of the flag (set for Session scope).

No Sharing:

Remember how Application variables could be shared by all viewers on your ASP web site? That's not so with Session Variables. They are private; Session Variables are to be accessed only by one user.

Session.Abandon( ):

My bet is you could figure out Session.Abandon() without any explanation. However, let me just state for the record that Session.Abandon() ends the user's session and releases the Session Variables from memory.

Session Properties:

Let's briefly discuss two properties you are not likely to use. Session.CodePage lets you call for foreign character sets, like Chinese or Russian. Session.LCID is a location identifier. It determines the time zone and language for the server. Don't mess with it.

Now let's move on to something you might actually use from time to time. Session.SessionID is a read-only property generated by the server, and assigned to one specific user during one specific session. The SessionID follows the user from the beginning of the session until the end.

Session.Timeout is the number of minutes that a user can be idle before the Server ends the user's individual session and reclaims the memory that was allocated to Session Variables. (Session.Timeout is demonstrated in the global.asa in lesson 10.)

Session Events:

The two Session events are Session_OnStart() and Session_OnEnd(). These events are accessed in the global.asa. You can see an example of global.asa in lesson 10.

What's Next:

We've seen in the last two lessons that Apartment Model Behavior is strictly forbidden in the Application Intrinsic Object. (It's not forbidden in the Session Object, but it is restricted.) So how do we store values (functions in particular) for reuse in many scripts? That is the subject of Lesson 13.


------------------------------- 13 -----------------------------------

nclude Files

Server Side Includes:

Experienced JavaScript programmers know that code reuse is good. Experienced JavaScript programmers also know that JavaScript functions are data types.

So, we should be able to store a JavaScript function inside a Session Variable or an Application Variable, right? Unfortunately, no. The way to reuse JavaScript functions across many pages is to use SSI: Server Side Includes.

<%@LANGUAGE="JavaScript"%>


ASP JavaScript Lessons(8-14)-speakitnow-ChinaUnix博客
  • 博客访问: 5547952
  • 博文数量: 915
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 5216
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-15 17:17
文章分类

全部博文(915)

文章存档

2011年(1)

2008年(134)

2007年(287)

2006年(493)

我的朋友
微信关注

IT168企业级官微



微信号:IT168qiye



系统架构师大会



微信号:SACC2013

订阅
热词专题
ASP JavaScript Lessons(8-14) 2006-12-31 14:48:22

分类: Java

-------------------------------- 8 -----------------------------------

The Request Object

Request Object:

Request has five (5) Collections, one (1) Property, and one (1) Method. You'll use the Collections far more than the property or the method.

Request Collections:

Below is a table of the Request Collections and descriptions of how they are used.

Request Collections
ClientCertificateRequest.ClientCertificate("Key[Field]")
Client security info for SSL encryption
CookiesRequest.Cookies("cookieName")
Holds cookie value stored on the client
FormRequest.Form("formName")
Holds value sent via HTML Form
QueryStringRequest.QueryString("keyName")
Name/Value pair appended to the end of the URL
ServerVariablesRequest.ServerVariables("variableName")
Hold values sent in the HTTP Headers

ClientCertificate:

Request.ClientCertificate is used with S.S.L. (Secure Sockets Layer). It is beyond the scope of this web site.

Cookies:

We will learn Request.Cookies and Response.Cookies together in Lesson 08. Please be patient.

Form:

Request.Form is probably the workhorse of the Request Collections. The first script is a repeat from Lesson 03.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

Type something into the text box and submit it.



How Much Money do you make each month?






Click Here to run script08.asp in a new window. It posts information to script08a.asp which is found below. In turn, script08a.asp posts information to script08b.asp which is also found below.

<%@LANGUAGE="JavaScript"%>
<%
var WebPageVariable = new String( Request.Form("WebPageVariable") )
WebPageVariable = WebPageVariable.toUpperCase();

var monthlySalary = new String( Request.Form("monthlySalary") )
monthlySalary = monthlySalary.toLowerCase();
%>

The Web Page Variable you typed is: <%=WebPageVariable%>

The monthly salary you listed is: <%=monthlySalary%>



Click the button to see Query Strings




We'll be using Request.Form when we "Post" an HTML form to the server. Notice that the NAME attribute in the HTML form corresponds to the "name" in Request.Form("name"). To be more specific, corresponds with Request.Form("WebPageVariable"). We already talked about the need for the new String( ) constructor back in Lesson 03.

QueryString:

We'll be using Request.QueryString when we use an HTML form to "Get" a page from the server. Request.QueryString() is very similar to Request.Form(). Take a look at script08b.asp which I printed below.

<%@LANGUAGE="JavaScript"%>
<%
var QueryVariable = new String( Request.QueryString("QueryVariable") )
%>

The QueryString Value is: <%=QueryVariable%>

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>
Click Here
for the link to script08b.asp?QueryVariable=<%=QueryVariable%>
<%
} //closing bracket for if statement.
%>

If you haven't already, Click Here to run script08.asp in a new window. Cycle through all the forms and links, and then come back.

You can use Request.QueryString in two different ways. You can either use an HTML form to "Get" a page from the server, which will generate a query string. Or you can manually build a query string and add it to the backside of a link. We'll dissect script08b.asp from top to bottom.

var QueryVariable = new String( Request.QueryString("QueryVariable") )

The line above in script08b.asp corresponds to the line below from script08a.asp


The NAME="someName" in the HTML form becomes the Request.QueryString("someName") on the next page.

About half way into script08b.asp are the lines I reprinted below.

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>

We've already converted Request.QueryString() into a JavaScript string at the top of the script. So, now we can do a string comparison.

If the QueryVariable hasn't already been set equal to "Lesson 08's new Query!" then we do that. Then we use the escape( ) method to convert white space and special characters into Unicode. (URL's should contain neither whitespace, nor most special characters.)

In lesson 14 we'll see a better way to encode URL's. When we study the Server Object, we'll see Server.URLEncode(). But for now, just know that escape() works.

You can have more than one QueryString on each page. If you lose count of your QueryStrings, then you use Request.QueryString.Count to tell you the number.

The Request Shortcut:

Request.Form() and Request.QueryString() share a shortcut. Request.Form("WebPageVariable") can be abbreviated as Request("WebPageVariable") and Request.QueryString("QueryVariable") can be abbreviated as Request("QueryVariable").

ServerVariables:

Server Variables represent the HTTP Headers sent to the server by the client. I won't demonstrate them all, because there are too many.

<%@LANGUAGE="JavaScript"%>










ALL_RAW<%=Request.ServerVariables("ALL_RAW")%>
REMOTE_ADDR<%=Request.ServerVariables("REMOTE_ADDR")%>
HTTP_USER_AGENT<%=Request.ServerVariables("HTTP_USER_AGENT")%>
URL<%=Request.ServerVariables("URL")%>


Click Here to run the script in a new window.

Demonstrated above are four (4) server variables. There are (give or take) about 50 server variables available. You can look up the full list of server variables for yourself on the internet.

Misc. Notes:

Request.BinaryRead() is the lone method and TotalBytes is the lone property. Request.BinaryRead(Request.TotalBytes) retrieves data from an HTML form using "POST." You must supply the TotalBytes as an argument. It stores the data into an array. BinaryRead cannot be used at the same time as Request.Form().

Next Stop, Cookies:

The only Request Collection I did not cover was Cookies. I want to cover Request.Cookies and Response.Cookies side by side. So we'll do that in Lesson 09.


-------------------------------- 9 -----------------------------------

ookies and Cookies

Response Cookies in General:

We'll start with the Response Cookies collection. I don't think it could be any easier. You simply put the name of the cookie in the argument. The corresponding value is a string. The only time it gets complicated is when you use keys (which I demonstrate below).

<%@LANGUAGE="JavaScript"%>
<%
var Tomorrow=new Date()
Tomorrow.setDate(Tomorrow.getDate() + 1)
myExpire = (Tomorrow.getMonth() + 1) + "/" + Tomorrow.getDate()
myExpire += "/" + Tomorrow.getFullYear()

Response.Cookies("firstCookie") = "I like cookies."
Response.Cookies("firstCookie").Expires=myExpire

Response.Cookies("secondCookie") = "ASP Cookies Are Easy."
Response.Cookies("secondCookie").Expires=myExpire

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."
Response.Cookies("thirdCookie").Expires=myExpire
%>


We're just setting <%=Response.Cookies.Count%> cookies.

Click Here to retrieve these cookies.

Click Here to run the script in a new window.

Setting a cookie with ASP is pretty simple. The format is Response.Cookies("name")="value". That "value" can be either a JavaScript string or an ASP native type such as Request.Form("userEmail").

Response Cookie Keys:

If on the first page of your ASP application Response.Cookies("myOnlyCookie") is set, and subsequently on page two of your application Response.Cookies("myOnlyCookie") is reassigned a second value, then only the second value will remain. The first value is lost in this circumstance.

The solution is to either use multiple cookies or to use multiple Keys in the SAME cookie.

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."

The Setting of one or more Keys is pretty simple. It follows this format: Response.Cookies("name")("key")="value". Again, the "value" can either be a JavaScript string or ASP native type. The advantage of using keys is that you can store multiple Key/Value pairs inside the very same cookie.

Request Cookies:

Generally you will find ASP cookie management to be far easier than Client Side JavaScript cookies. Down below is the script that retrieves the cookies.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
var firstCookie = Request.Cookies("firstCookie");
var secondCookie = Request.Cookies("secondCookie");
var thirdCookie2Keys = Request.Cookies("thirdCookie")("firstKey")
thirdCookie2Keys += " " + Request.Cookies("thirdCookie")("secondKey");
%>

There are <%=Request.Cookies.Count%> Cookies.

1) <%=firstCookie%>

2) <%=secondCookie%>

3) <%=thirdCookie2Keys%>

Click Here to see how we would sort cookies
if we didn't know their names.

Click Here to run the script in a new window.

Do I even need to explain "firstCookie" and "secondCookie"? It's so easy. However, I will have to have explain the retrieval of Keys in "thirdCookie".

We retrieve cookies in almost exactly the same way that we set them, and that goes for Keys as well. If you keep track of your Key names, then retrieving their values is pretty easy.

var thirdCookieFirstKey = Request.Cookies("thirdCookie")("firstKey")

Deleting Cookies:

To delete a cookie, give it an expiration date in the past. The following is not in our examples, but it would work.

var Yesterday=new Date()
Yesterday.setDate(Yesterday.getDate() - 1)
myExpire = (Yesterday.getMonth() + 1) + "/" + Yesterday.getDate()
myExpire += "/" + Yesterday.getFullYear()
Response.Cookies("firstCookie").Expires=myExpire

Cookie Crumbs:

What if you lose track of your cookie names? What if you lose your Keys? First of all, don't do that. But secondly, we have options.

We can use a VBScript Function with a for/each loop. We can use Javascript's new Enumerator( ) or we can use a pair of for Loops. We, however, cannot use JavaScript's for/in loop. This means we have to be creative.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
%>


<%
Response.Write("Let's use a VBScript function to ")
Response.Write("sort out the Cookies and Keys.

\r")
var longCookie = forEachCookie()
if (longCookie)
{
longCookie = longCookie.split("; ")
for (i=0;i<=longCookie.length-1;i++)
{
Response.Write(longCookie[ i ] + "
\r")
}
}
Response.Write("
\r")

Response.Write("Let's use new Enumerator( ) to ")
Response.Write("sort out the Cookies and Keys.

\r")
var myEnum = new Enumerator(Request.Cookies);
for (myEnum; !myEnum.atEnd() ; myEnum.moveNext() )
{
Response.Write(myEnum.item() + "=")
n=Request.Cookies(myEnum.item()).Count
if (n)
{
for (o=1;o<=n;o++)
{
Response.Write(Request.Cookies(myEnum.item())(o) + " ")
}
//Begin alternate method of using Enumerator()
Response.Write("
\rOR... ")
Response.Write(myEnum.item() + "=")
Response.Write(unescape(Request.Cookies(myEnum.item())))
//End alternate method
}
else
{
Response.Write(Request.Cookies(myEnum.item()))
}
Response.Write("
\r")
}
Response.Write("
\r")

Response.Write("Let's use a pair of JavaScript loops to ")
Response.Write("sort out the Cookies and Keys.

\r")
a=Request.Cookies.Count
for (b=1;b<=a;b++)
{
d = Request.Cookies(b).Count
if (d)
{
for (c=1;c<=d;c++)
{
Response.Write(Request.Cookies(b)(c) + " ")
}
Response.Write("
\r")
}
else
{
Response.Write(Request.Cookies(b) + "
\r")
}
}
%>

Click Here to run the script in a new window.

We do the same job three times. You decide for yourself which one you like best. In the first example you can plainly see from the script, I ask a VBScript function to find and break down all the cookies. I then output the data back to the waiting JavaScript variable.

var longCookie = forEachCookie()

What can I say? Don't lose track of your cookies and don't lose track of your Keys. Otherwise you might have to get a VBScript slim jim.

The new Enumerator() is okay. I use Enumerator two different ways; one way fails to capture the Key names, and the other way successfully captures the key names (but it needs unescape() to get the Key values to print normally).

In round three, I use a pair of for loops, but they're not as functional as for/in would be. (Notice the lack of Key names.)

Misc. Notes:

We didn't use new String( ) in this lesson. But remember, if you want to manipulate the cookie values inside JavaScript functions or methods, then you will need new String().

var firstCookie = new String(Request.Cookies("firstCookie") )
firstCookie = firstCookie.toUpperCase()

Also, if you were to use Client Side scripting to locate cookies, you would have noticed that there is an extra cookie. ASP keeps track of its sessions using a cookie.



------------------------------- 10 -----------------------------------

lobal ASA

Global.asa:

First of all, what is a global.asa? It's an optional script file that holds certain "global" information that you can access through the entire ASP appliciation. The global.asa is a plain text file saved with the .asa extension.

You should only have one global.asa and it should go in your top level directory.

Below is an example global.asa file. Don't try to understand the script just yet. We'll get to the specifics in the next two lessons.







List of Can Do's:

There are four things you can do with a global.asa.

1) Object Declarations
2) Application Events
3) Session Events
4) Library Reference.

I don't expect you understand any of that yet. Just remember, there are only a few things we can do with the global.asa. Let's move on to lesson 11.



------------------------------- 11 -----------------------------------

pplication Object

Overview:

The Application Object represents a collection of ASP pages. The Application object has zero (0) properties, two (2) collections, two (2) methods, and two (2) events.

Get Started:

Below are a couple scripts for lesson11.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>


Would you like to chose the official Application color?





No, click here.

Click Here to run script11.asp in a new window. Below is script11a.asp.

<%@LANGUAGE="JavaScript"%>

<%
Application.Lock()
var OfficialColor = new String( Request.Form("OfficialColor") )
if (OfficialColor=="red")
{
Application("OfficialColor") = "red"
}
if (OfficialColor=="white")
{
Application("OfficialColor") = "white"
}
if (OfficialColor=="blue")
{
Application("OfficialColor") = "blue"
}
if (OfficialColor=="undefined")
{
//Do nothing. Just leave the color alone.
}
Application.Unlock()
%>
">

The official application color is <%=Application("OfficialColor")%>.




Application Collections:

The two collections are Contents and StaticObjects. StaticObjects come in the form of the flag. That's done in the global.asa that we saw in Lesson 09. I'll demonstrate it again down below.

By contrast, the Contents collection is demonstrated above. It allows you to set and retrieve variables with Application scope. The format for setting an Application variable is Application.Contents("VariableName")="VariableValue". However, since Contents is the default Collection, we have a little shortcut for setting Application variables. The shortcut goes like this: Application("VariableName")="VariableValue".

Share the Variable:

One last thought on Application Variables. The application variable is shared by all visitors. Let's say that you and I are on the same ASP web site at the same time. If you set the background color to white in script11.asp, then I will see "white" as the official color if I go directly to script11a.asp. Application Variables are by no means the most efficient means of passing information from one user to another.

No Apartment Model:

You may notice that the example above seems to be inefficient. Why not just directly assign Application("OfficialColor") = Request.Form("OfficialColor")? Because we can't. By design, the newer (and updated) versions of Microsoft server software intentionally do not support Apartment Model Behavior.

Application Methods:

The two Application Methods are Lock() and Unlock(). Lock() blocks all other users from changing the Application variables. Unlock() releases control so that other users can change it. That's important on a larger site where multiple users may be trying to access the same page at the same time.

Application Events:

The two Application events are Application_OnStart() and Application_OnEnd(). These events are accessed in the global.asa. Let's repeat that script from lesson 09.







Misc. Items:

Application.Contents has two methods of its own. Application.Contents.Remove("VariableName") and Application.Contents.RemoveAll().

You'll notice there are also Session Events in the global.asa. We'll deal with those in Lesson 12. You'll also notice a call to the ADO Library. We'll talk about that when we get to databases.


------------------------------- 12 -----------------------------------

ession Object

Overview:

The Session Object is how you track a single user across many pages. It has four (4) properties, two (2) collections, one (1) method, and two (2) events.

Get Started:

In this series of examples we will create a password system. We will use the Session Object to track whether or not a user is authorized to view certain pages. Below are several scripts for lesson12. Look at them, play with, and then read the explanations that come further down the page.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

To play along with our password page, put in a user name and a password.


The correct user name is guest.

And the correct password is also guest.


User:

Pass:





Click Here to run script12.asp in a new window. Below is script12a.asp.

<%@LANGUAGE="JavaScript"%>
<%
var userName=new String(Request.Form("userName"))
var userPassword=new String(Request.Form("userPassword"))
if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}
else
{
Session("Authorized")=false
%>

You did not supply the correct Name & Password.

Click here to log in.

<%
} //end else statement
%>

We'll skip over script12b.asp entirely because it's almost exactly the same as script12c.asp. Down below is script12c.asp.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
%>

The second of two pages that are password protected.

Click Here to log out.

<%
} //end of else statement
%>

Above is script12c.asp, which is the second of two password-protected pages. Below is script12.asp, which is the logout page.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
var SessionID=Session.SessionID
Session.Abandon()
%>

You have sucessfully logged out.

This was session <%=SessionID%>.


Now try a link to one of the
pages you've already visited.


script12b.asp

script12c.asp

script12d.asp


<%
} //end of else statement
%>

A Quick Explanation:

After all that, the last thing you want to see is another grey box full of code. Sorry to do it one more time but, the keystone to this system is in script12a.asp. I've reprinted it down below.

if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}

Any page can now be turned into a password protected page with the following line: if (Session("Authorized")!=true). Session Variables are part of the Session Collections. Let's talk about them.

Session Collections:

The two Session Collections are Session.Contents and Session.StaticObjects. They parallel the Application.Contents and Application.StaticObjects.

Using Session.Contents("someVariable")="someValue" we can set Session Variables. These variables allow us to carry values from one page to the next. Since Contents is the default collection we can use a little shortcut. It goes like this: Session("someVariable")="someValue".

The shortcut is what you saw in the scripts above.

Session.Contents has two methods of its own. They are Session.Contents.Remove("variableName") and Session.Contents.RemoveAll().

We did not demonstrate StaticObjects in the scripts above. It comes in the form of the flag (set for Session scope).

No Sharing:

Remember how Application variables could be shared by all viewers on your ASP web site? That's not so with Session Variables. They are private; Session Variables are to be accessed only by one user.

Session.Abandon( ):

My bet is you could figure out Session.Abandon() without any explanation. However, let me just state for the record that Session.Abandon() ends the user's session and releases the Session Variables from memory.

Session Properties:

Let's briefly discuss two properties you are not likely to use. Session.CodePage lets you call for foreign character sets, like Chinese or Russian. Session.LCID is a location identifier. It determines the time zone and language for the server. Don't mess with it.

Now let's move on to something you might actually use from time to time. Session.SessionID is a read-only property generated by the server, and assigned to one specific user during one specific session. The SessionID follows the user from the beginning of the session until the end.

Session.Timeout is the number of minutes that a user can be idle before the Server ends the user's individual session and reclaims the memory that was allocated to Session Variables. (Session.Timeout is demonstrated in the global.asa in lesson 10.)

Session Events:

The two Session events are Session_OnStart() and Session_OnEnd(). These events are accessed in the global.asa. You can see an example of global.asa in lesson 10.

What's Next:

We've seen in the last two lessons that Apartment Model Behavior is strictly forbidden in the Application Intrinsic Object. (It's not forbidden in the Session Object, but it is restricted.) So how do we store values (functions in particular) for reuse in many scripts? That is the subject of Lesson 13.


------------------------------- 13 -----------------------------------

nclude Files

Server Side Includes:

Experienced JavaScript programmers know that code reuse is good. Experienced JavaScript programmers also know that JavaScript functions are data types.

So, we should be able to store a JavaScript function inside a Session Variable or an Application Variable, right? Unfortunately, no. The way to reuse JavaScript functions across many pages is to use SSI: Server Side Includes.

<%@LANGUAGE="JavaScript"%>


ASP JavaScript Lessons(8-14)-speakitnow-ChinaUnix博客
  • 博客访问: 5547953
  • 博文数量: 915
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 5216
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-15 17:17
文章分类

全部博文(915)

文章存档

2011年(1)

2008年(134)

2007年(287)

2006年(493)

我的朋友
微信关注

IT168企业级官微



微信号:IT168qiye



系统架构师大会



微信号:SACC2013

订阅
热词专题
ASP JavaScript Lessons(8-14) 2006-12-31 14:48:22

分类: Java

-------------------------------- 8 -----------------------------------

The Request Object

Request Object:

Request has five (5) Collections, one (1) Property, and one (1) Method. You'll use the Collections far more than the property or the method.

Request Collections:

Below is a table of the Request Collections and descriptions of how they are used.

Request Collections
ClientCertificateRequest.ClientCertificate("Key[Field]")
Client security info for SSL encryption
CookiesRequest.Cookies("cookieName")
Holds cookie value stored on the client
FormRequest.Form("formName")
Holds value sent via HTML Form
QueryStringRequest.QueryString("keyName")
Name/Value pair appended to the end of the URL
ServerVariablesRequest.ServerVariables("variableName")
Hold values sent in the HTTP Headers

ClientCertificate:

Request.ClientCertificate is used with S.S.L. (Secure Sockets Layer). It is beyond the scope of this web site.

Cookies:

We will learn Request.Cookies and Response.Cookies together in Lesson 08. Please be patient.

Form:

Request.Form is probably the workhorse of the Request Collections. The first script is a repeat from Lesson 03.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

Type something into the text box and submit it.



How Much Money do you make each month?






Click Here to run script08.asp in a new window. It posts information to script08a.asp which is found below. In turn, script08a.asp posts information to script08b.asp which is also found below.

<%@LANGUAGE="JavaScript"%>
<%
var WebPageVariable = new String( Request.Form("WebPageVariable") )
WebPageVariable = WebPageVariable.toUpperCase();

var monthlySalary = new String( Request.Form("monthlySalary") )
monthlySalary = monthlySalary.toLowerCase();
%>

The Web Page Variable you typed is: <%=WebPageVariable%>

The monthly salary you listed is: <%=monthlySalary%>



Click the button to see Query Strings




We'll be using Request.Form when we "Post" an HTML form to the server. Notice that the NAME attribute in the HTML form corresponds to the "name" in Request.Form("name"). To be more specific, corresponds with Request.Form("WebPageVariable"). We already talked about the need for the new String( ) constructor back in Lesson 03.

QueryString:

We'll be using Request.QueryString when we use an HTML form to "Get" a page from the server. Request.QueryString() is very similar to Request.Form(). Take a look at script08b.asp which I printed below.

<%@LANGUAGE="JavaScript"%>
<%
var QueryVariable = new String( Request.QueryString("QueryVariable") )
%>

The QueryString Value is: <%=QueryVariable%>

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>
Click Here
for the link to script08b.asp?QueryVariable=<%=QueryVariable%>
<%
} //closing bracket for if statement.
%>

If you haven't already, Click Here to run script08.asp in a new window. Cycle through all the forms and links, and then come back.

You can use Request.QueryString in two different ways. You can either use an HTML form to "Get" a page from the server, which will generate a query string. Or you can manually build a query string and add it to the backside of a link. We'll dissect script08b.asp from top to bottom.

var QueryVariable = new String( Request.QueryString("QueryVariable") )

The line above in script08b.asp corresponds to the line below from script08a.asp


The NAME="someName" in the HTML form becomes the Request.QueryString("someName") on the next page.

About half way into script08b.asp are the lines I reprinted below.

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>

We've already converted Request.QueryString() into a JavaScript string at the top of the script. So, now we can do a string comparison.

If the QueryVariable hasn't already been set equal to "Lesson 08's new Query!" then we do that. Then we use the escape( ) method to convert white space and special characters into Unicode. (URL's should contain neither whitespace, nor most special characters.)

In lesson 14 we'll see a better way to encode URL's. When we study the Server Object, we'll see Server.URLEncode(). But for now, just know that escape() works.

You can have more than one QueryString on each page. If you lose count of your QueryStrings, then you use Request.QueryString.Count to tell you the number.

The Request Shortcut:

Request.Form() and Request.QueryString() share a shortcut. Request.Form("WebPageVariable") can be abbreviated as Request("WebPageVariable") and Request.QueryString("QueryVariable") can be abbreviated as Request("QueryVariable").

ServerVariables:

Server Variables represent the HTTP Headers sent to the server by the client. I won't demonstrate them all, because there are too many.

<%@LANGUAGE="JavaScript"%>










ALL_RAW<%=Request.ServerVariables("ALL_RAW")%>
REMOTE_ADDR<%=Request.ServerVariables("REMOTE_ADDR")%>
HTTP_USER_AGENT<%=Request.ServerVariables("HTTP_USER_AGENT")%>
URL<%=Request.ServerVariables("URL")%>


Click Here to run the script in a new window.

Demonstrated above are four (4) server variables. There are (give or take) about 50 server variables available. You can look up the full list of server variables for yourself on the internet.

Misc. Notes:

Request.BinaryRead() is the lone method and TotalBytes is the lone property. Request.BinaryRead(Request.TotalBytes) retrieves data from an HTML form using "POST." You must supply the TotalBytes as an argument. It stores the data into an array. BinaryRead cannot be used at the same time as Request.Form().

Next Stop, Cookies:

The only Request Collection I did not cover was Cookies. I want to cover Request.Cookies and Response.Cookies side by side. So we'll do that in Lesson 09.


-------------------------------- 9 -----------------------------------

ookies and Cookies

Response Cookies in General:

We'll start with the Response Cookies collection. I don't think it could be any easier. You simply put the name of the cookie in the argument. The corresponding value is a string. The only time it gets complicated is when you use keys (which I demonstrate below).

<%@LANGUAGE="JavaScript"%>
<%
var Tomorrow=new Date()
Tomorrow.setDate(Tomorrow.getDate() + 1)
myExpire = (Tomorrow.getMonth() + 1) + "/" + Tomorrow.getDate()
myExpire += "/" + Tomorrow.getFullYear()

Response.Cookies("firstCookie") = "I like cookies."
Response.Cookies("firstCookie").Expires=myExpire

Response.Cookies("secondCookie") = "ASP Cookies Are Easy."
Response.Cookies("secondCookie").Expires=myExpire

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."
Response.Cookies("thirdCookie").Expires=myExpire
%>


We're just setting <%=Response.Cookies.Count%> cookies.

Click Here to retrieve these cookies.

Click Here to run the script in a new window.

Setting a cookie with ASP is pretty simple. The format is Response.Cookies("name")="value". That "value" can be either a JavaScript string or an ASP native type such as Request.Form("userEmail").

Response Cookie Keys:

If on the first page of your ASP application Response.Cookies("myOnlyCookie") is set, and subsequently on page two of your application Response.Cookies("myOnlyCookie") is reassigned a second value, then only the second value will remain. The first value is lost in this circumstance.

The solution is to either use multiple cookies or to use multiple Keys in the SAME cookie.

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."

The Setting of one or more Keys is pretty simple. It follows this format: Response.Cookies("name")("key")="value". Again, the "value" can either be a JavaScript string or ASP native type. The advantage of using keys is that you can store multiple Key/Value pairs inside the very same cookie.

Request Cookies:

Generally you will find ASP cookie management to be far easier than Client Side JavaScript cookies. Down below is the script that retrieves the cookies.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
var firstCookie = Request.Cookies("firstCookie");
var secondCookie = Request.Cookies("secondCookie");
var thirdCookie2Keys = Request.Cookies("thirdCookie")("firstKey")
thirdCookie2Keys += " " + Request.Cookies("thirdCookie")("secondKey");
%>

There are <%=Request.Cookies.Count%> Cookies.

1) <%=firstCookie%>

2) <%=secondCookie%>

3) <%=thirdCookie2Keys%>

Click Here to see how we would sort cookies
if we didn't know their names.

Click Here to run the script in a new window.

Do I even need to explain "firstCookie" and "secondCookie"? It's so easy. However, I will have to have explain the retrieval of Keys in "thirdCookie".

We retrieve cookies in almost exactly the same way that we set them, and that goes for Keys as well. If you keep track of your Key names, then retrieving their values is pretty easy.

var thirdCookieFirstKey = Request.Cookies("thirdCookie")("firstKey")

Deleting Cookies:

To delete a cookie, give it an expiration date in the past. The following is not in our examples, but it would work.

var Yesterday=new Date()
Yesterday.setDate(Yesterday.getDate() - 1)
myExpire = (Yesterday.getMonth() + 1) + "/" + Yesterday.getDate()
myExpire += "/" + Yesterday.getFullYear()
Response.Cookies("firstCookie").Expires=myExpire

Cookie Crumbs:

What if you lose track of your cookie names? What if you lose your Keys? First of all, don't do that. But secondly, we have options.

We can use a VBScript Function with a for/each loop. We can use Javascript's new Enumerator( ) or we can use a pair of for Loops. We, however, cannot use JavaScript's for/in loop. This means we have to be creative.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
%>


<%
Response.Write("Let's use a VBScript function to ")
Response.Write("sort out the Cookies and Keys.

\r")
var longCookie = forEachCookie()
if (longCookie)
{
longCookie = longCookie.split("; ")
for (i=0;i<=longCookie.length-1;i++)
{
Response.Write(longCookie[ i ] + "
\r")
}
}
Response.Write("
\r")

Response.Write("Let's use new Enumerator( ) to ")
Response.Write("sort out the Cookies and Keys.

\r")
var myEnum = new Enumerator(Request.Cookies);
for (myEnum; !myEnum.atEnd() ; myEnum.moveNext() )
{
Response.Write(myEnum.item() + "=")
n=Request.Cookies(myEnum.item()).Count
if (n)
{
for (o=1;o<=n;o++)
{
Response.Write(Request.Cookies(myEnum.item())(o) + " ")
}
//Begin alternate method of using Enumerator()
Response.Write("
\rOR... ")
Response.Write(myEnum.item() + "=")
Response.Write(unescape(Request.Cookies(myEnum.item())))
//End alternate method
}
else
{
Response.Write(Request.Cookies(myEnum.item()))
}
Response.Write("
\r")
}
Response.Write("
\r")

Response.Write("Let's use a pair of JavaScript loops to ")
Response.Write("sort out the Cookies and Keys.

\r")
a=Request.Cookies.Count
for (b=1;b<=a;b++)
{
d = Request.Cookies(b).Count
if (d)
{
for (c=1;c<=d;c++)
{
Response.Write(Request.Cookies(b)(c) + " ")
}
Response.Write("
\r")
}
else
{
Response.Write(Request.Cookies(b) + "
\r")
}
}
%>

Click Here to run the script in a new window.

We do the same job three times. You decide for yourself which one you like best. In the first example you can plainly see from the script, I ask a VBScript function to find and break down all the cookies. I then output the data back to the waiting JavaScript variable.

var longCookie = forEachCookie()

What can I say? Don't lose track of your cookies and don't lose track of your Keys. Otherwise you might have to get a VBScript slim jim.

The new Enumerator() is okay. I use Enumerator two different ways; one way fails to capture the Key names, and the other way successfully captures the key names (but it needs unescape() to get the Key values to print normally).

In round three, I use a pair of for loops, but they're not as functional as for/in would be. (Notice the lack of Key names.)

Misc. Notes:

We didn't use new String( ) in this lesson. But remember, if you want to manipulate the cookie values inside JavaScript functions or methods, then you will need new String().

var firstCookie = new String(Request.Cookies("firstCookie") )
firstCookie = firstCookie.toUpperCase()

Also, if you were to use Client Side scripting to locate cookies, you would have noticed that there is an extra cookie. ASP keeps track of its sessions using a cookie.



------------------------------- 10 -----------------------------------

lobal ASA

Global.asa:

First of all, what is a global.asa? It's an optional script file that holds certain "global" information that you can access through the entire ASP appliciation. The global.asa is a plain text file saved with the .asa extension.

You should only have one global.asa and it should go in your top level directory.

Below is an example global.asa file. Don't try to understand the script just yet. We'll get to the specifics in the next two lessons.







List of Can Do's:

There are four things you can do with a global.asa.

1) Object Declarations
2) Application Events
3) Session Events
4) Library Reference.

I don't expect you understand any of that yet. Just remember, there are only a few things we can do with the global.asa. Let's move on to lesson 11.



------------------------------- 11 -----------------------------------

pplication Object

Overview:

The Application Object represents a collection of ASP pages. The Application object has zero (0) properties, two (2) collections, two (2) methods, and two (2) events.

Get Started:

Below are a couple scripts for lesson11.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>


Would you like to chose the official Application color?





No, click here.

Click Here to run script11.asp in a new window. Below is script11a.asp.

<%@LANGUAGE="JavaScript"%>

<%
Application.Lock()
var OfficialColor = new String( Request.Form("OfficialColor") )
if (OfficialColor=="red")
{
Application("OfficialColor") = "red"
}
if (OfficialColor=="white")
{
Application("OfficialColor") = "white"
}
if (OfficialColor=="blue")
{
Application("OfficialColor") = "blue"
}
if (OfficialColor=="undefined")
{
//Do nothing. Just leave the color alone.
}
Application.Unlock()
%>
">

The official application color is <%=Application("OfficialColor")%>.




Application Collections:

The two collections are Contents and StaticObjects. StaticObjects come in the form of the flag. That's done in the global.asa that we saw in Lesson 09. I'll demonstrate it again down below.

By contrast, the Contents collection is demonstrated above. It allows you to set and retrieve variables with Application scope. The format for setting an Application variable is Application.Contents("VariableName")="VariableValue". However, since Contents is the default Collection, we have a little shortcut for setting Application variables. The shortcut goes like this: Application("VariableName")="VariableValue".

Share the Variable:

One last thought on Application Variables. The application variable is shared by all visitors. Let's say that you and I are on the same ASP web site at the same time. If you set the background color to white in script11.asp, then I will see "white" as the official color if I go directly to script11a.asp. Application Variables are by no means the most efficient means of passing information from one user to another.

No Apartment Model:

You may notice that the example above seems to be inefficient. Why not just directly assign Application("OfficialColor") = Request.Form("OfficialColor")? Because we can't. By design, the newer (and updated) versions of Microsoft server software intentionally do not support Apartment Model Behavior.

Application Methods:

The two Application Methods are Lock() and Unlock(). Lock() blocks all other users from changing the Application variables. Unlock() releases control so that other users can change it. That's important on a larger site where multiple users may be trying to access the same page at the same time.

Application Events:

The two Application events are Application_OnStart() and Application_OnEnd(). These events are accessed in the global.asa. Let's repeat that script from lesson 09.







Misc. Items:

Application.Contents has two methods of its own. Application.Contents.Remove("VariableName") and Application.Contents.RemoveAll().

You'll notice there are also Session Events in the global.asa. We'll deal with those in Lesson 12. You'll also notice a call to the ADO Library. We'll talk about that when we get to databases.


------------------------------- 12 -----------------------------------

ession Object

Overview:

The Session Object is how you track a single user across many pages. It has four (4) properties, two (2) collections, one (1) method, and two (2) events.

Get Started:

In this series of examples we will create a password system. We will use the Session Object to track whether or not a user is authorized to view certain pages. Below are several scripts for lesson12. Look at them, play with, and then read the explanations that come further down the page.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

To play along with our password page, put in a user name and a password.


The correct user name is guest.

And the correct password is also guest.


User:

Pass:





Click Here to run script12.asp in a new window. Below is script12a.asp.

<%@LANGUAGE="JavaScript"%>
<%
var userName=new String(Request.Form("userName"))
var userPassword=new String(Request.Form("userPassword"))
if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}
else
{
Session("Authorized")=false
%>

You did not supply the correct Name & Password.

Click here to log in.

<%
} //end else statement
%>

We'll skip over script12b.asp entirely because it's almost exactly the same as script12c.asp. Down below is script12c.asp.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
%>

The second of two pages that are password protected.

Click Here to log out.

<%
} //end of else statement
%>

Above is script12c.asp, which is the second of two password-protected pages. Below is script12.asp, which is the logout page.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
var SessionID=Session.SessionID
Session.Abandon()
%>

You have sucessfully logged out.

This was session <%=SessionID%>.


Now try a link to one of the
pages you've already visited.


script12b.asp

script12c.asp

script12d.asp


<%
} //end of else statement
%>

A Quick Explanation:

After all that, the last thing you want to see is another grey box full of code. Sorry to do it one more time but, the keystone to this system is in script12a.asp. I've reprinted it down below.

if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}

Any page can now be turned into a password protected page with the following line: if (Session("Authorized")!=true). Session Variables are part of the Session Collections. Let's talk about them.

Session Collections:

The two Session Collections are Session.Contents and Session.StaticObjects. They parallel the Application.Contents and Application.StaticObjects.

Using Session.Contents("someVariable")="someValue" we can set Session Variables. These variables allow us to carry values from one page to the next. Since Contents is the default collection we can use a little shortcut. It goes like this: Session("someVariable")="someValue".

The shortcut is what you saw in the scripts above.

Session.Contents has two methods of its own. They are Session.Contents.Remove("variableName") and Session.Contents.RemoveAll().

We did not demonstrate StaticObjects in the scripts above. It comes in the form of the flag (set for Session scope).

No Sharing:

Remember how Application variables could be shared by all viewers on your ASP web site? That's not so with Session Variables. They are private; Session Variables are to be accessed only by one user.

Session.Abandon( ):

My bet is you could figure out Session.Abandon() without any explanation. However, let me just state for the record that Session.Abandon() ends the user's session and releases the Session Variables from memory.

Session Properties:

Let's briefly discuss two properties you are not likely to use. Session.CodePage lets you call for foreign character sets, like Chinese or Russian. Session.LCID is a location identifier. It determines the time zone and language for the server. Don't mess with it.

Now let's move on to something you might actually use from time to time. Session.SessionID is a read-only property generated by the server, and assigned to one specific user during one specific session. The SessionID follows the user from the beginning of the session until the end.

Session.Timeout is the number of minutes that a user can be idle before the Server ends the user's individual session and reclaims the memory that was allocated to Session Variables. (Session.Timeout is demonstrated in the global.asa in lesson 10.)

Session Events:

The two Session events are Session_OnStart() and Session_OnEnd(). These events are accessed in the global.asa. You can see an example of global.asa in lesson 10.

What's Next:

We've seen in the last two lessons that Apartment Model Behavior is strictly forbidden in the Application Intrinsic Object. (It's not forbidden in the Session Object, but it is restricted.) So how do we store values (functions in particular) for reuse in many scripts? That is the subject of Lesson 13.


------------------------------- 13 -----------------------------------

nclude Files

Server Side Includes:

Experienced JavaScript programmers know that code reuse is good. Experienced JavaScript programmers also know that JavaScript functions are data types.

So, we should be able to store a JavaScript function inside a Session Variable or an Application Variable, right? Unfortunately, no. The way to reuse JavaScript functions across many pages is to use SSI: Server Side Includes.

<%@LANGUAGE="JavaScript"%>


ASP JavaScript Lessons(8-14)-speakitnow-ChinaUnix博客
  • 博客访问: 5547954
  • 博文数量: 915
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 5216
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-15 17:17
文章分类

全部博文(915)

文章存档

2011年(1)

2008年(134)

2007年(287)

2006年(493)

我的朋友
微信关注

IT168企业级官微



微信号:IT168qiye



系统架构师大会



微信号:SACC2013

订阅
热词专题
ASP JavaScript Lessons(8-14) 2006-12-31 14:48:22

分类: Java

-------------------------------- 8 -----------------------------------

The Request Object

Request Object:

Request has five (5) Collections, one (1) Property, and one (1) Method. You'll use the Collections far more than the property or the method.

Request Collections:

Below is a table of the Request Collections and descriptions of how they are used.

Request Collections
ClientCertificateRequest.ClientCertificate("Key[Field]")
Client security info for SSL encryption
CookiesRequest.Cookies("cookieName")
Holds cookie value stored on the client
FormRequest.Form("formName")
Holds value sent via HTML Form
QueryStringRequest.QueryString("keyName")
Name/Value pair appended to the end of the URL
ServerVariablesRequest.ServerVariables("variableName")
Hold values sent in the HTTP Headers

ClientCertificate:

Request.ClientCertificate is used with S.S.L. (Secure Sockets Layer). It is beyond the scope of this web site.

Cookies:

We will learn Request.Cookies and Response.Cookies together in Lesson 08. Please be patient.

Form:

Request.Form is probably the workhorse of the Request Collections. The first script is a repeat from Lesson 03.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

Type something into the text box and submit it.



How Much Money do you make each month?






Click Here to run script08.asp in a new window. It posts information to script08a.asp which is found below. In turn, script08a.asp posts information to script08b.asp which is also found below.

<%@LANGUAGE="JavaScript"%>
<%
var WebPageVariable = new String( Request.Form("WebPageVariable") )
WebPageVariable = WebPageVariable.toUpperCase();

var monthlySalary = new String( Request.Form("monthlySalary") )
monthlySalary = monthlySalary.toLowerCase();
%>

The Web Page Variable you typed is: <%=WebPageVariable%>

The monthly salary you listed is: <%=monthlySalary%>



Click the button to see Query Strings




We'll be using Request.Form when we "Post" an HTML form to the server. Notice that the NAME attribute in the HTML form corresponds to the "name" in Request.Form("name"). To be more specific, corresponds with Request.Form("WebPageVariable"). We already talked about the need for the new String( ) constructor back in Lesson 03.

QueryString:

We'll be using Request.QueryString when we use an HTML form to "Get" a page from the server. Request.QueryString() is very similar to Request.Form(). Take a look at script08b.asp which I printed below.

<%@LANGUAGE="JavaScript"%>
<%
var QueryVariable = new String( Request.QueryString("QueryVariable") )
%>

The QueryString Value is: <%=QueryVariable%>

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>
Click Here
for the link to script08b.asp?QueryVariable=<%=QueryVariable%>
<%
} //closing bracket for if statement.
%>

If you haven't already, Click Here to run script08.asp in a new window. Cycle through all the forms and links, and then come back.

You can use Request.QueryString in two different ways. You can either use an HTML form to "Get" a page from the server, which will generate a query string. Or you can manually build a query string and add it to the backside of a link. We'll dissect script08b.asp from top to bottom.

var QueryVariable = new String( Request.QueryString("QueryVariable") )

The line above in script08b.asp corresponds to the line below from script08a.asp


The NAME="someName" in the HTML form becomes the Request.QueryString("someName") on the next page.

About half way into script08b.asp are the lines I reprinted below.

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>

We've already converted Request.QueryString() into a JavaScript string at the top of the script. So, now we can do a string comparison.

If the QueryVariable hasn't already been set equal to "Lesson 08's new Query!" then we do that. Then we use the escape( ) method to convert white space and special characters into Unicode. (URL's should contain neither whitespace, nor most special characters.)

In lesson 14 we'll see a better way to encode URL's. When we study the Server Object, we'll see Server.URLEncode(). But for now, just know that escape() works.

You can have more than one QueryString on each page. If you lose count of your QueryStrings, then you use Request.QueryString.Count to tell you the number.

The Request Shortcut:

Request.Form() and Request.QueryString() share a shortcut. Request.Form("WebPageVariable") can be abbreviated as Request("WebPageVariable") and Request.QueryString("QueryVariable") can be abbreviated as Request("QueryVariable").

ServerVariables:

Server Variables represent the HTTP Headers sent to the server by the client. I won't demonstrate them all, because there are too many.

<%@LANGUAGE="JavaScript"%>










ALL_RAW<%=Request.ServerVariables("ALL_RAW")%>
REMOTE_ADDR<%=Request.ServerVariables("REMOTE_ADDR")%>
HTTP_USER_AGENT<%=Request.ServerVariables("HTTP_USER_AGENT")%>
URL<%=Request.ServerVariables("URL")%>


Click Here to run the script in a new window.

Demonstrated above are four (4) server variables. There are (give or take) about 50 server variables available. You can look up the full list of server variables for yourself on the internet.

Misc. Notes:

Request.BinaryRead() is the lone method and TotalBytes is the lone property. Request.BinaryRead(Request.TotalBytes) retrieves data from an HTML form using "POST." You must supply the TotalBytes as an argument. It stores the data into an array. BinaryRead cannot be used at the same time as Request.Form().

Next Stop, Cookies:

The only Request Collection I did not cover was Cookies. I want to cover Request.Cookies and Response.Cookies side by side. So we'll do that in Lesson 09.


-------------------------------- 9 -----------------------------------

ookies and Cookies

Response Cookies in General:

We'll start with the Response Cookies collection. I don't think it could be any easier. You simply put the name of the cookie in the argument. The corresponding value is a string. The only time it gets complicated is when you use keys (which I demonstrate below).

<%@LANGUAGE="JavaScript"%>
<%
var Tomorrow=new Date()
Tomorrow.setDate(Tomorrow.getDate() + 1)
myExpire = (Tomorrow.getMonth() + 1) + "/" + Tomorrow.getDate()
myExpire += "/" + Tomorrow.getFullYear()

Response.Cookies("firstCookie") = "I like cookies."
Response.Cookies("firstCookie").Expires=myExpire

Response.Cookies("secondCookie") = "ASP Cookies Are Easy."
Response.Cookies("secondCookie").Expires=myExpire

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."
Response.Cookies("thirdCookie").Expires=myExpire
%>


We're just setting <%=Response.Cookies.Count%> cookies.

Click Here to retrieve these cookies.

Click Here to run the script in a new window.

Setting a cookie with ASP is pretty simple. The format is Response.Cookies("name")="value". That "value" can be either a JavaScript string or an ASP native type such as Request.Form("userEmail").

Response Cookie Keys:

If on the first page of your ASP application Response.Cookies("myOnlyCookie") is set, and subsequently on page two of your application Response.Cookies("myOnlyCookie") is reassigned a second value, then only the second value will remain. The first value is lost in this circumstance.

The solution is to either use multiple cookies or to use multiple Keys in the SAME cookie.

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."

The Setting of one or more Keys is pretty simple. It follows this format: Response.Cookies("name")("key")="value". Again, the "value" can either be a JavaScript string or ASP native type. The advantage of using keys is that you can store multiple Key/Value pairs inside the very same cookie.

Request Cookies:

Generally you will find ASP cookie management to be far easier than Client Side JavaScript cookies. Down below is the script that retrieves the cookies.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
var firstCookie = Request.Cookies("firstCookie");
var secondCookie = Request.Cookies("secondCookie");
var thirdCookie2Keys = Request.Cookies("thirdCookie")("firstKey")
thirdCookie2Keys += " " + Request.Cookies("thirdCookie")("secondKey");
%>

There are <%=Request.Cookies.Count%> Cookies.

1) <%=firstCookie%>

2) <%=secondCookie%>

3) <%=thirdCookie2Keys%>

Click Here to see how we would sort cookies
if we didn't know their names.

Click Here to run the script in a new window.

Do I even need to explain "firstCookie" and "secondCookie"? It's so easy. However, I will have to have explain the retrieval of Keys in "thirdCookie".

We retrieve cookies in almost exactly the same way that we set them, and that goes for Keys as well. If you keep track of your Key names, then retrieving their values is pretty easy.

var thirdCookieFirstKey = Request.Cookies("thirdCookie")("firstKey")

Deleting Cookies:

To delete a cookie, give it an expiration date in the past. The following is not in our examples, but it would work.

var Yesterday=new Date()
Yesterday.setDate(Yesterday.getDate() - 1)
myExpire = (Yesterday.getMonth() + 1) + "/" + Yesterday.getDate()
myExpire += "/" + Yesterday.getFullYear()
Response.Cookies("firstCookie").Expires=myExpire

Cookie Crumbs:

What if you lose track of your cookie names? What if you lose your Keys? First of all, don't do that. But secondly, we have options.

We can use a VBScript Function with a for/each loop. We can use Javascript's new Enumerator( ) or we can use a pair of for Loops. We, however, cannot use JavaScript's for/in loop. This means we have to be creative.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
%>


<%
Response.Write("Let's use a VBScript function to ")
Response.Write("sort out the Cookies and Keys.

\r")
var longCookie = forEachCookie()
if (longCookie)
{
longCookie = longCookie.split("; ")
for (i=0;i<=longCookie.length-1;i++)
{
Response.Write(longCookie[ i ] + "
\r")
}
}
Response.Write("
\r")

Response.Write("Let's use new Enumerator( ) to ")
Response.Write("sort out the Cookies and Keys.

\r")
var myEnum = new Enumerator(Request.Cookies);
for (myEnum; !myEnum.atEnd() ; myEnum.moveNext() )
{
Response.Write(myEnum.item() + "=")
n=Request.Cookies(myEnum.item()).Count
if (n)
{
for (o=1;o<=n;o++)
{
Response.Write(Request.Cookies(myEnum.item())(o) + " ")
}
//Begin alternate method of using Enumerator()
Response.Write("
\rOR... ")
Response.Write(myEnum.item() + "=")
Response.Write(unescape(Request.Cookies(myEnum.item())))
//End alternate method
}
else
{
Response.Write(Request.Cookies(myEnum.item()))
}
Response.Write("
\r")
}
Response.Write("
\r")

Response.Write("Let's use a pair of JavaScript loops to ")
Response.Write("sort out the Cookies and Keys.

\r")
a=Request.Cookies.Count
for (b=1;b<=a;b++)
{
d = Request.Cookies(b).Count
if (d)
{
for (c=1;c<=d;c++)
{
Response.Write(Request.Cookies(b)(c) + " ")
}
Response.Write("
\r")
}
else
{
Response.Write(Request.Cookies(b) + "
\r")
}
}
%>

Click Here to run the script in a new window.

We do the same job three times. You decide for yourself which one you like best. In the first example you can plainly see from the script, I ask a VBScript function to find and break down all the cookies. I then output the data back to the waiting JavaScript variable.

var longCookie = forEachCookie()

What can I say? Don't lose track of your cookies and don't lose track of your Keys. Otherwise you might have to get a VBScript slim jim.

The new Enumerator() is okay. I use Enumerator two different ways; one way fails to capture the Key names, and the other way successfully captures the key names (but it needs unescape() to get the Key values to print normally).

In round three, I use a pair of for loops, but they're not as functional as for/in would be. (Notice the lack of Key names.)

Misc. Notes:

We didn't use new String( ) in this lesson. But remember, if you want to manipulate the cookie values inside JavaScript functions or methods, then you will need new String().

var firstCookie = new String(Request.Cookies("firstCookie") )
firstCookie = firstCookie.toUpperCase()

Also, if you were to use Client Side scripting to locate cookies, you would have noticed that there is an extra cookie. ASP keeps track of its sessions using a cookie.



------------------------------- 10 -----------------------------------

lobal ASA

Global.asa:

First of all, what is a global.asa? It's an optional script file that holds certain "global" information that you can access through the entire ASP appliciation. The global.asa is a plain text file saved with the .asa extension.

You should only have one global.asa and it should go in your top level directory.

Below is an example global.asa file. Don't try to understand the script just yet. We'll get to the specifics in the next two lessons.







List of Can Do's:

There are four things you can do with a global.asa.

1) Object Declarations
2) Application Events
3) Session Events
4) Library Reference.

I don't expect you understand any of that yet. Just remember, there are only a few things we can do with the global.asa. Let's move on to lesson 11.



------------------------------- 11 -----------------------------------

pplication Object

Overview:

The Application Object represents a collection of ASP pages. The Application object has zero (0) properties, two (2) collections, two (2) methods, and two (2) events.

Get Started:

Below are a couple scripts for lesson11.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>


Would you like to chose the official Application color?





No, click here.

Click Here to run script11.asp in a new window. Below is script11a.asp.

<%@LANGUAGE="JavaScript"%>

<%
Application.Lock()
var OfficialColor = new String( Request.Form("OfficialColor") )
if (OfficialColor=="red")
{
Application("OfficialColor") = "red"
}
if (OfficialColor=="white")
{
Application("OfficialColor") = "white"
}
if (OfficialColor=="blue")
{
Application("OfficialColor") = "blue"
}
if (OfficialColor=="undefined")
{
//Do nothing. Just leave the color alone.
}
Application.Unlock()
%>
">

The official application color is <%=Application("OfficialColor")%>.




Application Collections:

The two collections are Contents and StaticObjects. StaticObjects come in the form of the flag. That's done in the global.asa that we saw in Lesson 09. I'll demonstrate it again down below.

By contrast, the Contents collection is demonstrated above. It allows you to set and retrieve variables with Application scope. The format for setting an Application variable is Application.Contents("VariableName")="VariableValue". However, since Contents is the default Collection, we have a little shortcut for setting Application variables. The shortcut goes like this: Application("VariableName")="VariableValue".

Share the Variable:

One last thought on Application Variables. The application variable is shared by all visitors. Let's say that you and I are on the same ASP web site at the same time. If you set the background color to white in script11.asp, then I will see "white" as the official color if I go directly to script11a.asp. Application Variables are by no means the most efficient means of passing information from one user to another.

No Apartment Model:

You may notice that the example above seems to be inefficient. Why not just directly assign Application("OfficialColor") = Request.Form("OfficialColor")? Because we can't. By design, the newer (and updated) versions of Microsoft server software intentionally do not support Apartment Model Behavior.

Application Methods:

The two Application Methods are Lock() and Unlock(). Lock() blocks all other users from changing the Application variables. Unlock() releases control so that other users can change it. That's important on a larger site where multiple users may be trying to access the same page at the same time.

Application Events:

The two Application events are Application_OnStart() and Application_OnEnd(). These events are accessed in the global.asa. Let's repeat that script from lesson 09.







Misc. Items:

Application.Contents has two methods of its own. Application.Contents.Remove("VariableName") and Application.Contents.RemoveAll().

You'll notice there are also Session Events in the global.asa. We'll deal with those in Lesson 12. You'll also notice a call to the ADO Library. We'll talk about that when we get to databases.


------------------------------- 12 -----------------------------------

ession Object

Overview:

The Session Object is how you track a single user across many pages. It has four (4) properties, two (2) collections, one (1) method, and two (2) events.

Get Started:

In this series of examples we will create a password system. We will use the Session Object to track whether or not a user is authorized to view certain pages. Below are several scripts for lesson12. Look at them, play with, and then read the explanations that come further down the page.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

To play along with our password page, put in a user name and a password.


The correct user name is guest.

And the correct password is also guest.


User:

Pass:





Click Here to run script12.asp in a new window. Below is script12a.asp.

<%@LANGUAGE="JavaScript"%>
<%
var userName=new String(Request.Form("userName"))
var userPassword=new String(Request.Form("userPassword"))
if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}
else
{
Session("Authorized")=false
%>

You did not supply the correct Name & Password.

Click here to log in.

<%
} //end else statement
%>

We'll skip over script12b.asp entirely because it's almost exactly the same as script12c.asp. Down below is script12c.asp.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
%>

The second of two pages that are password protected.

Click Here to log out.

<%
} //end of else statement
%>

Above is script12c.asp, which is the second of two password-protected pages. Below is script12.asp, which is the logout page.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
var SessionID=Session.SessionID
Session.Abandon()
%>

You have sucessfully logged out.

This was session <%=SessionID%>.


Now try a link to one of the
pages you've already visited.


script12b.asp

script12c.asp

script12d.asp


<%
} //end of else statement
%>

A Quick Explanation:

After all that, the last thing you want to see is another grey box full of code. Sorry to do it one more time but, the keystone to this system is in script12a.asp. I've reprinted it down below.

if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}

Any page can now be turned into a password protected page with the following line: if (Session("Authorized")!=true). Session Variables are part of the Session Collections. Let's talk about them.

Session Collections:

The two Session Collections are Session.Contents and Session.StaticObjects. They parallel the Application.Contents and Application.StaticObjects.

Using Session.Contents("someVariable")="someValue" we can set Session Variables. These variables allow us to carry values from one page to the next. Since Contents is the default collection we can use a little shortcut. It goes like this: Session("someVariable")="someValue".

The shortcut is what you saw in the scripts above.

Session.Contents has two methods of its own. They are Session.Contents.Remove("variableName") and Session.Contents.RemoveAll().

We did not demonstrate StaticObjects in the scripts above. It comes in the form of the flag (set for Session scope).

No Sharing:

Remember how Application variables could be shared by all viewers on your ASP web site? That's not so with Session Variables. They are private; Session Variables are to be accessed only by one user.

Session.Abandon( ):

My bet is you could figure out Session.Abandon() without any explanation. However, let me just state for the record that Session.Abandon() ends the user's session and releases the Session Variables from memory.

Session Properties:

Let's briefly discuss two properties you are not likely to use. Session.CodePage lets you call for foreign character sets, like Chinese or Russian. Session.LCID is a location identifier. It determines the time zone and language for the server. Don't mess with it.

Now let's move on to something you might actually use from time to time. Session.SessionID is a read-only property generated by the server, and assigned to one specific user during one specific session. The SessionID follows the user from the beginning of the session until the end.

Session.Timeout is the number of minutes that a user can be idle before the Server ends the user's individual session and reclaims the memory that was allocated to Session Variables. (Session.Timeout is demonstrated in the global.asa in lesson 10.)

Session Events:

The two Session events are Session_OnStart() and Session_OnEnd(). These events are accessed in the global.asa. You can see an example of global.asa in lesson 10.

What's Next:

We've seen in the last two lessons that Apartment Model Behavior is strictly forbidden in the Application Intrinsic Object. (It's not forbidden in the Session Object, but it is restricted.) So how do we store values (functions in particular) for reuse in many scripts? That is the subject of Lesson 13.


------------------------------- 13 -----------------------------------

nclude Files

Server Side Includes:

Experienced JavaScript programmers know that code reuse is good. Experienced JavaScript programmers also know that JavaScript functions are data types.

So, we should be able to store a JavaScript function inside a Session Variable or an Application Variable, right? Unfortunately, no. The way to reuse JavaScript functions across many pages is to use SSI: Server Side Includes.

<%@LANGUAGE="JavaScript"%>


ASP JavaScript Lessons(8-14)-speakitnow-ChinaUnix博客
  • 博客访问: 5547955
  • 博文数量: 915
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 5216
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-15 17:17
文章分类

全部博文(915)

文章存档

2011年(1)

2008年(134)

2007年(287)

2006年(493)

我的朋友
微信关注

IT168企业级官微



微信号:IT168qiye



系统架构师大会



微信号:SACC2013

订阅
热词专题
ASP JavaScript Lessons(8-14) 2006-12-31 14:48:22

分类: Java

-------------------------------- 8 -----------------------------------

The Request Object

Request Object:

Request has five (5) Collections, one (1) Property, and one (1) Method. You'll use the Collections far more than the property or the method.

Request Collections:

Below is a table of the Request Collections and descriptions of how they are used.

Request Collections
ClientCertificateRequest.ClientCertificate("Key[Field]")
Client security info for SSL encryption
CookiesRequest.Cookies("cookieName")
Holds cookie value stored on the client
FormRequest.Form("formName")
Holds value sent via HTML Form
QueryStringRequest.QueryString("keyName")
Name/Value pair appended to the end of the URL
ServerVariablesRequest.ServerVariables("variableName")
Hold values sent in the HTTP Headers

ClientCertificate:

Request.ClientCertificate is used with S.S.L. (Secure Sockets Layer). It is beyond the scope of this web site.

Cookies:

We will learn Request.Cookies and Response.Cookies together in Lesson 08. Please be patient.

Form:

Request.Form is probably the workhorse of the Request Collections. The first script is a repeat from Lesson 03.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

Type something into the text box and submit it.



How Much Money do you make each month?






Click Here to run script08.asp in a new window. It posts information to script08a.asp which is found below. In turn, script08a.asp posts information to script08b.asp which is also found below.

<%@LANGUAGE="JavaScript"%>
<%
var WebPageVariable = new String( Request.Form("WebPageVariable") )
WebPageVariable = WebPageVariable.toUpperCase();

var monthlySalary = new String( Request.Form("monthlySalary") )
monthlySalary = monthlySalary.toLowerCase();
%>

The Web Page Variable you typed is: <%=WebPageVariable%>

The monthly salary you listed is: <%=monthlySalary%>



Click the button to see Query Strings




We'll be using Request.Form when we "Post" an HTML form to the server. Notice that the NAME attribute in the HTML form corresponds to the "name" in Request.Form("name"). To be more specific, corresponds with Request.Form("WebPageVariable"). We already talked about the need for the new String( ) constructor back in Lesson 03.

QueryString:

We'll be using Request.QueryString when we use an HTML form to "Get" a page from the server. Request.QueryString() is very similar to Request.Form(). Take a look at script08b.asp which I printed below.

<%@LANGUAGE="JavaScript"%>
<%
var QueryVariable = new String( Request.QueryString("QueryVariable") )
%>

The QueryString Value is: <%=QueryVariable%>

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>
Click Here
for the link to script08b.asp?QueryVariable=<%=QueryVariable%>
<%
} //closing bracket for if statement.
%>

If you haven't already, Click Here to run script08.asp in a new window. Cycle through all the forms and links, and then come back.

You can use Request.QueryString in two different ways. You can either use an HTML form to "Get" a page from the server, which will generate a query string. Or you can manually build a query string and add it to the backside of a link. We'll dissect script08b.asp from top to bottom.

var QueryVariable = new String( Request.QueryString("QueryVariable") )

The line above in script08b.asp corresponds to the line below from script08a.asp


The NAME="someName" in the HTML form becomes the Request.QueryString("someName") on the next page.

About half way into script08b.asp are the lines I reprinted below.

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>

We've already converted Request.QueryString() into a JavaScript string at the top of the script. So, now we can do a string comparison.

If the QueryVariable hasn't already been set equal to "Lesson 08's new Query!" then we do that. Then we use the escape( ) method to convert white space and special characters into Unicode. (URL's should contain neither whitespace, nor most special characters.)

In lesson 14 we'll see a better way to encode URL's. When we study the Server Object, we'll see Server.URLEncode(). But for now, just know that escape() works.

You can have more than one QueryString on each page. If you lose count of your QueryStrings, then you use Request.QueryString.Count to tell you the number.

The Request Shortcut:

Request.Form() and Request.QueryString() share a shortcut. Request.Form("WebPageVariable") can be abbreviated as Request("WebPageVariable") and Request.QueryString("QueryVariable") can be abbreviated as Request("QueryVariable").

ServerVariables:

Server Variables represent the HTTP Headers sent to the server by the client. I won't demonstrate them all, because there are too many.

<%@LANGUAGE="JavaScript"%>










ALL_RAW<%=Request.ServerVariables("ALL_RAW")%>
REMOTE_ADDR<%=Request.ServerVariables("REMOTE_ADDR")%>
HTTP_USER_AGENT<%=Request.ServerVariables("HTTP_USER_AGENT")%>
URL<%=Request.ServerVariables("URL")%>


Click Here to run the script in a new window.

Demonstrated above are four (4) server variables. There are (give or take) about 50 server variables available. You can look up the full list of server variables for yourself on the internet.

Misc. Notes:

Request.BinaryRead() is the lone method and TotalBytes is the lone property. Request.BinaryRead(Request.TotalBytes) retrieves data from an HTML form using "POST." You must supply the TotalBytes as an argument. It stores the data into an array. BinaryRead cannot be used at the same time as Request.Form().

Next Stop, Cookies:

The only Request Collection I did not cover was Cookies. I want to cover Request.Cookies and Response.Cookies side by side. So we'll do that in Lesson 09.


-------------------------------- 9 -----------------------------------

ookies and Cookies

Response Cookies in General:

We'll start with the Response Cookies collection. I don't think it could be any easier. You simply put the name of the cookie in the argument. The corresponding value is a string. The only time it gets complicated is when you use keys (which I demonstrate below).

<%@LANGUAGE="JavaScript"%>
<%
var Tomorrow=new Date()
Tomorrow.setDate(Tomorrow.getDate() + 1)
myExpire = (Tomorrow.getMonth() + 1) + "/" + Tomorrow.getDate()
myExpire += "/" + Tomorrow.getFullYear()

Response.Cookies("firstCookie") = "I like cookies."
Response.Cookies("firstCookie").Expires=myExpire

Response.Cookies("secondCookie") = "ASP Cookies Are Easy."
Response.Cookies("secondCookie").Expires=myExpire

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."
Response.Cookies("thirdCookie").Expires=myExpire
%>


We're just setting <%=Response.Cookies.Count%> cookies.

Click Here to retrieve these cookies.

Click Here to run the script in a new window.

Setting a cookie with ASP is pretty simple. The format is Response.Cookies("name")="value". That "value" can be either a JavaScript string or an ASP native type such as Request.Form("userEmail").

Response Cookie Keys:

If on the first page of your ASP application Response.Cookies("myOnlyCookie") is set, and subsequently on page two of your application Response.Cookies("myOnlyCookie") is reassigned a second value, then only the second value will remain. The first value is lost in this circumstance.

The solution is to either use multiple cookies or to use multiple Keys in the SAME cookie.

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."

The Setting of one or more Keys is pretty simple. It follows this format: Response.Cookies("name")("key")="value". Again, the "value" can either be a JavaScript string or ASP native type. The advantage of using keys is that you can store multiple Key/Value pairs inside the very same cookie.

Request Cookies:

Generally you will find ASP cookie management to be far easier than Client Side JavaScript cookies. Down below is the script that retrieves the cookies.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
var firstCookie = Request.Cookies("firstCookie");
var secondCookie = Request.Cookies("secondCookie");
var thirdCookie2Keys = Request.Cookies("thirdCookie")("firstKey")
thirdCookie2Keys += " " + Request.Cookies("thirdCookie")("secondKey");
%>

There are <%=Request.Cookies.Count%> Cookies.

1) <%=firstCookie%>

2) <%=secondCookie%>

3) <%=thirdCookie2Keys%>

Click Here to see how we would sort cookies
if we didn't know their names.

Click Here to run the script in a new window.

Do I even need to explain "firstCookie" and "secondCookie"? It's so easy. However, I will have to have explain the retrieval of Keys in "thirdCookie".

We retrieve cookies in almost exactly the same way that we set them, and that goes for Keys as well. If you keep track of your Key names, then retrieving their values is pretty easy.

var thirdCookieFirstKey = Request.Cookies("thirdCookie")("firstKey")

Deleting Cookies:

To delete a cookie, give it an expiration date in the past. The following is not in our examples, but it would work.

var Yesterday=new Date()
Yesterday.setDate(Yesterday.getDate() - 1)
myExpire = (Yesterday.getMonth() + 1) + "/" + Yesterday.getDate()
myExpire += "/" + Yesterday.getFullYear()
Response.Cookies("firstCookie").Expires=myExpire

Cookie Crumbs:

What if you lose track of your cookie names? What if you lose your Keys? First of all, don't do that. But secondly, we have options.

We can use a VBScript Function with a for/each loop. We can use Javascript's new Enumerator( ) or we can use a pair of for Loops. We, however, cannot use JavaScript's for/in loop. This means we have to be creative.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
%>


<%
Response.Write("Let's use a VBScript function to ")
Response.Write("sort out the Cookies and Keys.

\r")
var longCookie = forEachCookie()
if (longCookie)
{
longCookie = longCookie.split("; ")
for (i=0;i<=longCookie.length-1;i++)
{
Response.Write(longCookie[ i ] + "
\r")
}
}
Response.Write("
\r")

Response.Write("Let's use new Enumerator( ) to ")
Response.Write("sort out the Cookies and Keys.

\r")
var myEnum = new Enumerator(Request.Cookies);
for (myEnum; !myEnum.atEnd() ; myEnum.moveNext() )
{
Response.Write(myEnum.item() + "=")
n=Request.Cookies(myEnum.item()).Count
if (n)
{
for (o=1;o<=n;o++)
{
Response.Write(Request.Cookies(myEnum.item())(o) + " ")
}
//Begin alternate method of using Enumerator()
Response.Write("
\rOR... ")
Response.Write(myEnum.item() + "=")
Response.Write(unescape(Request.Cookies(myEnum.item())))
//End alternate method
}
else
{
Response.Write(Request.Cookies(myEnum.item()))
}
Response.Write("
\r")
}
Response.Write("
\r")

Response.Write("Let's use a pair of JavaScript loops to ")
Response.Write("sort out the Cookies and Keys.

\r")
a=Request.Cookies.Count
for (b=1;b<=a;b++)
{
d = Request.Cookies(b).Count
if (d)
{
for (c=1;c<=d;c++)
{
Response.Write(Request.Cookies(b)(c) + " ")
}
Response.Write("
\r")
}
else
{
Response.Write(Request.Cookies(b) + "
\r")
}
}
%>

Click Here to run the script in a new window.

We do the same job three times. You decide for yourself which one you like best. In the first example you can plainly see from the script, I ask a VBScript function to find and break down all the cookies. I then output the data back to the waiting JavaScript variable.

var longCookie = forEachCookie()

What can I say? Don't lose track of your cookies and don't lose track of your Keys. Otherwise you might have to get a VBScript slim jim.

The new Enumerator() is okay. I use Enumerator two different ways; one way fails to capture the Key names, and the other way successfully captures the key names (but it needs unescape() to get the Key values to print normally).

In round three, I use a pair of for loops, but they're not as functional as for/in would be. (Notice the lack of Key names.)

Misc. Notes:

We didn't use new String( ) in this lesson. But remember, if you want to manipulate the cookie values inside JavaScript functions or methods, then you will need new String().

var firstCookie = new String(Request.Cookies("firstCookie") )
firstCookie = firstCookie.toUpperCase()

Also, if you were to use Client Side scripting to locate cookies, you would have noticed that there is an extra cookie. ASP keeps track of its sessions using a cookie.



------------------------------- 10 -----------------------------------

lobal ASA

Global.asa:

First of all, what is a global.asa? It's an optional script file that holds certain "global" information that you can access through the entire ASP appliciation. The global.asa is a plain text file saved with the .asa extension.

You should only have one global.asa and it should go in your top level directory.

Below is an example global.asa file. Don't try to understand the script just yet. We'll get to the specifics in the next two lessons.







List of Can Do's:

There are four things you can do with a global.asa.

1) Object Declarations
2) Application Events
3) Session Events
4) Library Reference.

I don't expect you understand any of that yet. Just remember, there are only a few things we can do with the global.asa. Let's move on to lesson 11.



------------------------------- 11 -----------------------------------

pplication Object

Overview:

The Application Object represents a collection of ASP pages. The Application object has zero (0) properties, two (2) collections, two (2) methods, and two (2) events.

Get Started:

Below are a couple scripts for lesson11.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>


Would you like to chose the official Application color?





No, click here.

Click Here to run script11.asp in a new window. Below is script11a.asp.

<%@LANGUAGE="JavaScript"%>

<%
Application.Lock()
var OfficialColor = new String( Request.Form("OfficialColor") )
if (OfficialColor=="red")
{
Application("OfficialColor") = "red"
}
if (OfficialColor=="white")
{
Application("OfficialColor") = "white"
}
if (OfficialColor=="blue")
{
Application("OfficialColor") = "blue"
}
if (OfficialColor=="undefined")
{
//Do nothing. Just leave the color alone.
}
Application.Unlock()
%>
">

The official application color is <%=Application("OfficialColor")%>.




Application Collections:

The two collections are Contents and StaticObjects. StaticObjects come in the form of the flag. That's done in the global.asa that we saw in Lesson 09. I'll demonstrate it again down below.

By contrast, the Contents collection is demonstrated above. It allows you to set and retrieve variables with Application scope. The format for setting an Application variable is Application.Contents("VariableName")="VariableValue". However, since Contents is the default Collection, we have a little shortcut for setting Application variables. The shortcut goes like this: Application("VariableName")="VariableValue".

Share the Variable:

One last thought on Application Variables. The application variable is shared by all visitors. Let's say that you and I are on the same ASP web site at the same time. If you set the background color to white in script11.asp, then I will see "white" as the official color if I go directly to script11a.asp. Application Variables are by no means the most efficient means of passing information from one user to another.

No Apartment Model:

You may notice that the example above seems to be inefficient. Why not just directly assign Application("OfficialColor") = Request.Form("OfficialColor")? Because we can't. By design, the newer (and updated) versions of Microsoft server software intentionally do not support Apartment Model Behavior.

Application Methods:

The two Application Methods are Lock() and Unlock(). Lock() blocks all other users from changing the Application variables. Unlock() releases control so that other users can change it. That's important on a larger site where multiple users may be trying to access the same page at the same time.

Application Events:

The two Application events are Application_OnStart() and Application_OnEnd(). These events are accessed in the global.asa. Let's repeat that script from lesson 09.







Misc. Items:

Application.Contents has two methods of its own. Application.Contents.Remove("VariableName") and Application.Contents.RemoveAll().

You'll notice there are also Session Events in the global.asa. We'll deal with those in Lesson 12. You'll also notice a call to the ADO Library. We'll talk about that when we get to databases.


------------------------------- 12 -----------------------------------

ession Object

Overview:

The Session Object is how you track a single user across many pages. It has four (4) properties, two (2) collections, one (1) method, and two (2) events.

Get Started:

In this series of examples we will create a password system. We will use the Session Object to track whether or not a user is authorized to view certain pages. Below are several scripts for lesson12. Look at them, play with, and then read the explanations that come further down the page.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

To play along with our password page, put in a user name and a password.


The correct user name is guest.

And the correct password is also guest.


User:

Pass:





Click Here to run script12.asp in a new window. Below is script12a.asp.

<%@LANGUAGE="JavaScript"%>
<%
var userName=new String(Request.Form("userName"))
var userPassword=new String(Request.Form("userPassword"))
if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}
else
{
Session("Authorized")=false
%>

You did not supply the correct Name & Password.

Click here to log in.

<%
} //end else statement
%>

We'll skip over script12b.asp entirely because it's almost exactly the same as script12c.asp. Down below is script12c.asp.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
%>

The second of two pages that are password protected.

Click Here to log out.

<%
} //end of else statement
%>

Above is script12c.asp, which is the second of two password-protected pages. Below is script12.asp, which is the logout page.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
var SessionID=Session.SessionID
Session.Abandon()
%>

You have sucessfully logged out.

This was session <%=SessionID%>.


Now try a link to one of the
pages you've already visited.


script12b.asp

script12c.asp

script12d.asp


<%
} //end of else statement
%>

A Quick Explanation:

After all that, the last thing you want to see is another grey box full of code. Sorry to do it one more time but, the keystone to this system is in script12a.asp. I've reprinted it down below.

if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}

Any page can now be turned into a password protected page with the following line: if (Session("Authorized")!=true). Session Variables are part of the Session Collections. Let's talk about them.

Session Collections:

The two Session Collections are Session.Contents and Session.StaticObjects. They parallel the Application.Contents and Application.StaticObjects.

Using Session.Contents("someVariable")="someValue" we can set Session Variables. These variables allow us to carry values from one page to the next. Since Contents is the default collection we can use a little shortcut. It goes like this: Session("someVariable")="someValue".

The shortcut is what you saw in the scripts above.

Session.Contents has two methods of its own. They are Session.Contents.Remove("variableName") and Session.Contents.RemoveAll().

We did not demonstrate StaticObjects in the scripts above. It comes in the form of the flag (set for Session scope).

No Sharing:

Remember how Application variables could be shared by all viewers on your ASP web site? That's not so with Session Variables. They are private; Session Variables are to be accessed only by one user.

Session.Abandon( ):

My bet is you could figure out Session.Abandon() without any explanation. However, let me just state for the record that Session.Abandon() ends the user's session and releases the Session Variables from memory.

Session Properties:

Let's briefly discuss two properties you are not likely to use. Session.CodePage lets you call for foreign character sets, like Chinese or Russian. Session.LCID is a location identifier. It determines the time zone and language for the server. Don't mess with it.

Now let's move on to something you might actually use from time to time. Session.SessionID is a read-only property generated by the server, and assigned to one specific user during one specific session. The SessionID follows the user from the beginning of the session until the end.

Session.Timeout is the number of minutes that a user can be idle before the Server ends the user's individual session and reclaims the memory that was allocated to Session Variables. (Session.Timeout is demonstrated in the global.asa in lesson 10.)

Session Events:

The two Session events are Session_OnStart() and Session_OnEnd(). These events are accessed in the global.asa. You can see an example of global.asa in lesson 10.

What's Next:

We've seen in the last two lessons that Apartment Model Behavior is strictly forbidden in the Application Intrinsic Object. (It's not forbidden in the Session Object, but it is restricted.) So how do we store values (functions in particular) for reuse in many scripts? That is the subject of Lesson 13.


------------------------------- 13 -----------------------------------

nclude Files

Server Side Includes:

Experienced JavaScript programmers know that code reuse is good. Experienced JavaScript programmers also know that JavaScript functions are data types.

So, we should be able to store a JavaScript function inside a Session Variable or an Application Variable, right? Unfortunately, no. The way to reuse JavaScript functions across many pages is to use SSI: Server Side Includes.

<%@LANGUAGE="JavaScript"%>


ASP JavaScript Lessons(8-14)-speakitnow-ChinaUnix博客
  • 博客访问: 5547946
  • 博文数量: 915
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 5216
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-15 17:17
文章分类

全部博文(915)

文章存档

2011年(1)

2008年(134)

2007年(287)

2006年(493)

我的朋友
微信关注

IT168企业级官微



微信号:IT168qiye



系统架构师大会



微信号:SACC2013

订阅
热词专题
ASP JavaScript Lessons(8-14) 2006-12-31 14:48:22

分类: Java

-------------------------------- 8 -----------------------------------

The Request Object

Request Object:

Request has five (5) Collections, one (1) Property, and one (1) Method. You'll use the Collections far more than the property or the method.

Request Collections:

Below is a table of the Request Collections and descriptions of how they are used.

Request Collections
ClientCertificateRequest.ClientCertificate("Key[Field]")
Client security info for SSL encryption
CookiesRequest.Cookies("cookieName")
Holds cookie value stored on the client
FormRequest.Form("formName")
Holds value sent via HTML Form
QueryStringRequest.QueryString("keyName")
Name/Value pair appended to the end of the URL
ServerVariablesRequest.ServerVariables("variableName")
Hold values sent in the HTTP Headers

ClientCertificate:

Request.ClientCertificate is used with S.S.L. (Secure Sockets Layer). It is beyond the scope of this web site.

Cookies:

We will learn Request.Cookies and Response.Cookies together in Lesson 08. Please be patient.

Form:

Request.Form is probably the workhorse of the Request Collections. The first script is a repeat from Lesson 03.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

Type something into the text box and submit it.



How Much Money do you make each month?






Click Here to run script08.asp in a new window. It posts information to script08a.asp which is found below. In turn, script08a.asp posts information to script08b.asp which is also found below.

<%@LANGUAGE="JavaScript"%>
<%
var WebPageVariable = new String( Request.Form("WebPageVariable") )
WebPageVariable = WebPageVariable.toUpperCase();

var monthlySalary = new String( Request.Form("monthlySalary") )
monthlySalary = monthlySalary.toLowerCase();
%>

The Web Page Variable you typed is: <%=WebPageVariable%>

The monthly salary you listed is: <%=monthlySalary%>



Click the button to see Query Strings




We'll be using Request.Form when we "Post" an HTML form to the server. Notice that the NAME attribute in the HTML form corresponds to the "name" in Request.Form("name"). To be more specific, corresponds with Request.Form("WebPageVariable"). We already talked about the need for the new String( ) constructor back in Lesson 03.

QueryString:

We'll be using Request.QueryString when we use an HTML form to "Get" a page from the server. Request.QueryString() is very similar to Request.Form(). Take a look at script08b.asp which I printed below.

<%@LANGUAGE="JavaScript"%>
<%
var QueryVariable = new String( Request.QueryString("QueryVariable") )
%>

The QueryString Value is: <%=QueryVariable%>

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>
Click Here
for the link to script08b.asp?QueryVariable=<%=QueryVariable%>
<%
} //closing bracket for if statement.
%>

If you haven't already, Click Here to run script08.asp in a new window. Cycle through all the forms and links, and then come back.

You can use Request.QueryString in two different ways. You can either use an HTML form to "Get" a page from the server, which will generate a query string. Or you can manually build a query string and add it to the backside of a link. We'll dissect script08b.asp from top to bottom.

var QueryVariable = new String( Request.QueryString("QueryVariable") )

The line above in script08b.asp corresponds to the line below from script08a.asp


The NAME="someName" in the HTML form becomes the Request.QueryString("someName") on the next page.

About half way into script08b.asp are the lines I reprinted below.

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>

We've already converted Request.QueryString() into a JavaScript string at the top of the script. So, now we can do a string comparison.

If the QueryVariable hasn't already been set equal to "Lesson 08's new Query!" then we do that. Then we use the escape( ) method to convert white space and special characters into Unicode. (URL's should contain neither whitespace, nor most special characters.)

In lesson 14 we'll see a better way to encode URL's. When we study the Server Object, we'll see Server.URLEncode(). But for now, just know that escape() works.

You can have more than one QueryString on each page. If you lose count of your QueryStrings, then you use Request.QueryString.Count to tell you the number.

The Request Shortcut:

Request.Form() and Request.QueryString() share a shortcut. Request.Form("WebPageVariable") can be abbreviated as Request("WebPageVariable") and Request.QueryString("QueryVariable") can be abbreviated as Request("QueryVariable").

ServerVariables:

Server Variables represent the HTTP Headers sent to the server by the client. I won't demonstrate them all, because there are too many.

<%@LANGUAGE="JavaScript"%>










ALL_RAW<%=Request.ServerVariables("ALL_RAW")%>
REMOTE_ADDR<%=Request.ServerVariables("REMOTE_ADDR")%>
HTTP_USER_AGENT<%=Request.ServerVariables("HTTP_USER_AGENT")%>
URL<%=Request.ServerVariables("URL")%>


Click Here to run the script in a new window.

Demonstrated above are four (4) server variables. There are (give or take) about 50 server variables available. You can look up the full list of server variables for yourself on the internet.

Misc. Notes:

Request.BinaryRead() is the lone method and TotalBytes is the lone property. Request.BinaryRead(Request.TotalBytes) retrieves data from an HTML form using "POST." You must supply the TotalBytes as an argument. It stores the data into an array. BinaryRead cannot be used at the same time as Request.Form().

Next Stop, Cookies:

The only Request Collection I did not cover was Cookies. I want to cover Request.Cookies and Response.Cookies side by side. So we'll do that in Lesson 09.


-------------------------------- 9 -----------------------------------

ookies and Cookies

Response Cookies in General:

We'll start with the Response Cookies collection. I don't think it could be any easier. You simply put the name of the cookie in the argument. The corresponding value is a string. The only time it gets complicated is when you use keys (which I demonstrate below).

<%@LANGUAGE="JavaScript"%>
<%
var Tomorrow=new Date()
Tomorrow.setDate(Tomorrow.getDate() + 1)
myExpire = (Tomorrow.getMonth() + 1) + "/" + Tomorrow.getDate()
myExpire += "/" + Tomorrow.getFullYear()

Response.Cookies("firstCookie") = "I like cookies."
Response.Cookies("firstCookie").Expires=myExpire

Response.Cookies("secondCookie") = "ASP Cookies Are Easy."
Response.Cookies("secondCookie").Expires=myExpire

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."
Response.Cookies("thirdCookie").Expires=myExpire
%>


We're just setting <%=Response.Cookies.Count%> cookies.

Click Here to retrieve these cookies.

Click Here to run the script in a new window.

Setting a cookie with ASP is pretty simple. The format is Response.Cookies("name")="value". That "value" can be either a JavaScript string or an ASP native type such as Request.Form("userEmail").

Response Cookie Keys:

If on the first page of your ASP application Response.Cookies("myOnlyCookie") is set, and subsequently on page two of your application Response.Cookies("myOnlyCookie") is reassigned a second value, then only the second value will remain. The first value is lost in this circumstance.

The solution is to either use multiple cookies or to use multiple Keys in the SAME cookie.

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."

The Setting of one or more Keys is pretty simple. It follows this format: Response.Cookies("name")("key")="value". Again, the "value" can either be a JavaScript string or ASP native type. The advantage of using keys is that you can store multiple Key/Value pairs inside the very same cookie.

Request Cookies:

Generally you will find ASP cookie management to be far easier than Client Side JavaScript cookies. Down below is the script that retrieves the cookies.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
var firstCookie = Request.Cookies("firstCookie");
var secondCookie = Request.Cookies("secondCookie");
var thirdCookie2Keys = Request.Cookies("thirdCookie")("firstKey")
thirdCookie2Keys += " " + Request.Cookies("thirdCookie")("secondKey");
%>

There are <%=Request.Cookies.Count%> Cookies.

1) <%=firstCookie%>

2) <%=secondCookie%>

3) <%=thirdCookie2Keys%>

Click Here to see how we would sort cookies
if we didn't know their names.

Click Here to run the script in a new window.

Do I even need to explain "firstCookie" and "secondCookie"? It's so easy. However, I will have to have explain the retrieval of Keys in "thirdCookie".

We retrieve cookies in almost exactly the same way that we set them, and that goes for Keys as well. If you keep track of your Key names, then retrieving their values is pretty easy.

var thirdCookieFirstKey = Request.Cookies("thirdCookie")("firstKey")

Deleting Cookies:

To delete a cookie, give it an expiration date in the past. The following is not in our examples, but it would work.

var Yesterday=new Date()
Yesterday.setDate(Yesterday.getDate() - 1)
myExpire = (Yesterday.getMonth() + 1) + "/" + Yesterday.getDate()
myExpire += "/" + Yesterday.getFullYear()
Response.Cookies("firstCookie").Expires=myExpire

Cookie Crumbs:

What if you lose track of your cookie names? What if you lose your Keys? First of all, don't do that. But secondly, we have options.

We can use a VBScript Function with a for/each loop. We can use Javascript's new Enumerator( ) or we can use a pair of for Loops. We, however, cannot use JavaScript's for/in loop. This means we have to be creative.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
%>


<%
Response.Write("Let's use a VBScript function to ")
Response.Write("sort out the Cookies and Keys.

\r")
var longCookie = forEachCookie()
if (longCookie)
{
longCookie = longCookie.split("; ")
for (i=0;i<=longCookie.length-1;i++)
{
Response.Write(longCookie[ i ] + "
\r")
}
}
Response.Write("
\r")

Response.Write("Let's use new Enumerator( ) to ")
Response.Write("sort out the Cookies and Keys.

\r")
var myEnum = new Enumerator(Request.Cookies);
for (myEnum; !myEnum.atEnd() ; myEnum.moveNext() )
{
Response.Write(myEnum.item() + "=")
n=Request.Cookies(myEnum.item()).Count
if (n)
{
for (o=1;o<=n;o++)
{
Response.Write(Request.Cookies(myEnum.item())(o) + " ")
}
//Begin alternate method of using Enumerator()
Response.Write("
\rOR... ")
Response.Write(myEnum.item() + "=")
Response.Write(unescape(Request.Cookies(myEnum.item())))
//End alternate method
}
else
{
Response.Write(Request.Cookies(myEnum.item()))
}
Response.Write("
\r")
}
Response.Write("
\r")

Response.Write("Let's use a pair of JavaScript loops to ")
Response.Write("sort out the Cookies and Keys.

\r")
a=Request.Cookies.Count
for (b=1;b<=a;b++)
{
d = Request.Cookies(b).Count
if (d)
{
for (c=1;c<=d;c++)
{
Response.Write(Request.Cookies(b)(c) + " ")
}
Response.Write("
\r")
}
else
{
Response.Write(Request.Cookies(b) + "
\r")
}
}
%>

Click Here to run the script in a new window.

We do the same job three times. You decide for yourself which one you like best. In the first example you can plainly see from the script, I ask a VBScript function to find and break down all the cookies. I then output the data back to the waiting JavaScript variable.

var longCookie = forEachCookie()

What can I say? Don't lose track of your cookies and don't lose track of your Keys. Otherwise you might have to get a VBScript slim jim.

The new Enumerator() is okay. I use Enumerator two different ways; one way fails to capture the Key names, and the other way successfully captures the key names (but it needs unescape() to get the Key values to print normally).

In round three, I use a pair of for loops, but they're not as functional as for/in would be. (Notice the lack of Key names.)

Misc. Notes:

We didn't use new String( ) in this lesson. But remember, if you want to manipulate the cookie values inside JavaScript functions or methods, then you will need new String().

var firstCookie = new String(Request.Cookies("firstCookie") )
firstCookie = firstCookie.toUpperCase()

Also, if you were to use Client Side scripting to locate cookies, you would have noticed that there is an extra cookie. ASP keeps track of its sessions using a cookie.



------------------------------- 10 -----------------------------------

lobal ASA

Global.asa:

First of all, what is a global.asa? It's an optional script file that holds certain "global" information that you can access through the entire ASP appliciation. The global.asa is a plain text file saved with the .asa extension.

You should only have one global.asa and it should go in your top level directory.

Below is an example global.asa file. Don't try to understand the script just yet. We'll get to the specifics in the next two lessons.







List of Can Do's:

There are four things you can do with a global.asa.

1) Object Declarations
2) Application Events
3) Session Events
4) Library Reference.

I don't expect you understand any of that yet. Just remember, there are only a few things we can do with the global.asa. Let's move on to lesson 11.



------------------------------- 11 -----------------------------------

pplication Object

Overview:

The Application Object represents a collection of ASP pages. The Application object has zero (0) properties, two (2) collections, two (2) methods, and two (2) events.

Get Started:

Below are a couple scripts for lesson11.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>


Would you like to chose the official Application color?





No, click here.

Click Here to run script11.asp in a new window. Below is script11a.asp.

<%@LANGUAGE="JavaScript"%>

<%
Application.Lock()
var OfficialColor = new String( Request.Form("OfficialColor") )
if (OfficialColor=="red")
{
Application("OfficialColor") = "red"
}
if (OfficialColor=="white")
{
Application("OfficialColor") = "white"
}
if (OfficialColor=="blue")
{
Application("OfficialColor") = "blue"
}
if (OfficialColor=="undefined")
{
//Do nothing. Just leave the color alone.
}
Application.Unlock()
%>
">

The official application color is <%=Application("OfficialColor")%>.




Application Collections:

The two collections are Contents and StaticObjects. StaticObjects come in the form of the flag. That's done in the global.asa that we saw in Lesson 09. I'll demonstrate it again down below.

By contrast, the Contents collection is demonstrated above. It allows you to set and retrieve variables with Application scope. The format for setting an Application variable is Application.Contents("VariableName")="VariableValue". However, since Contents is the default Collection, we have a little shortcut for setting Application variables. The shortcut goes like this: Application("VariableName")="VariableValue".

Share the Variable:

One last thought on Application Variables. The application variable is shared by all visitors. Let's say that you and I are on the same ASP web site at the same time. If you set the background color to white in script11.asp, then I will see "white" as the official color if I go directly to script11a.asp. Application Variables are by no means the most efficient means of passing information from one user to another.

No Apartment Model:

You may notice that the example above seems to be inefficient. Why not just directly assign Application("OfficialColor") = Request.Form("OfficialColor")? Because we can't. By design, the newer (and updated) versions of Microsoft server software intentionally do not support Apartment Model Behavior.

Application Methods:

The two Application Methods are Lock() and Unlock(). Lock() blocks all other users from changing the Application variables. Unlock() releases control so that other users can change it. That's important on a larger site where multiple users may be trying to access the same page at the same time.

Application Events:

The two Application events are Application_OnStart() and Application_OnEnd(). These events are accessed in the global.asa. Let's repeat that script from lesson 09.







Misc. Items:

Application.Contents has two methods of its own. Application.Contents.Remove("VariableName") and Application.Contents.RemoveAll().

You'll notice there are also Session Events in the global.asa. We'll deal with those in Lesson 12. You'll also notice a call to the ADO Library. We'll talk about that when we get to databases.


------------------------------- 12 -----------------------------------

ession Object

Overview:

The Session Object is how you track a single user across many pages. It has four (4) properties, two (2) collections, one (1) method, and two (2) events.

Get Started:

In this series of examples we will create a password system. We will use the Session Object to track whether or not a user is authorized to view certain pages. Below are several scripts for lesson12. Look at them, play with, and then read the explanations that come further down the page.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

To play along with our password page, put in a user name and a password.


The correct user name is guest.

And the correct password is also guest.


User:

Pass:





Click Here to run script12.asp in a new window. Below is script12a.asp.

<%@LANGUAGE="JavaScript"%>
<%
var userName=new String(Request.Form("userName"))
var userPassword=new String(Request.Form("userPassword"))
if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}
else
{
Session("Authorized")=false
%>

You did not supply the correct Name & Password.

Click here to log in.

<%
} //end else statement
%>

We'll skip over script12b.asp entirely because it's almost exactly the same as script12c.asp. Down below is script12c.asp.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
%>

The second of two pages that are password protected.

Click Here to log out.

<%
} //end of else statement
%>

Above is script12c.asp, which is the second of two password-protected pages. Below is script12.asp, which is the logout page.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
var SessionID=Session.SessionID
Session.Abandon()
%>

You have sucessfully logged out.

This was session <%=SessionID%>.


Now try a link to one of the
pages you've already visited.


script12b.asp

script12c.asp

script12d.asp


<%
} //end of else statement
%>

A Quick Explanation:

After all that, the last thing you want to see is another grey box full of code. Sorry to do it one more time but, the keystone to this system is in script12a.asp. I've reprinted it down below.

if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}

Any page can now be turned into a password protected page with the following line: if (Session("Authorized")!=true). Session Variables are part of the Session Collections. Let's talk about them.

Session Collections:

The two Session Collections are Session.Contents and Session.StaticObjects. They parallel the Application.Contents and Application.StaticObjects.

Using Session.Contents("someVariable")="someValue" we can set Session Variables. These variables allow us to carry values from one page to the next. Since Contents is the default collection we can use a little shortcut. It goes like this: Session("someVariable")="someValue".

The shortcut is what you saw in the scripts above.

Session.Contents has two methods of its own. They are Session.Contents.Remove("variableName") and Session.Contents.RemoveAll().

We did not demonstrate StaticObjects in the scripts above. It comes in the form of the flag (set for Session scope).

No Sharing:

Remember how Application variables could be shared by all viewers on your ASP web site? That's not so with Session Variables. They are private; Session Variables are to be accessed only by one user.

Session.Abandon( ):

My bet is you could figure out Session.Abandon() without any explanation. However, let me just state for the record that Session.Abandon() ends the user's session and releases the Session Variables from memory.

Session Properties:

Let's briefly discuss two properties you are not likely to use. Session.CodePage lets you call for foreign character sets, like Chinese or Russian. Session.LCID is a location identifier. It determines the time zone and language for the server. Don't mess with it.

Now let's move on to something you might actually use from time to time. Session.SessionID is a read-only property generated by the server, and assigned to one specific user during one specific session. The SessionID follows the user from the beginning of the session until the end.

Session.Timeout is the number of minutes that a user can be idle before the Server ends the user's individual session and reclaims the memory that was allocated to Session Variables. (Session.Timeout is demonstrated in the global.asa in lesson 10.)

Session Events:

The two Session events are Session_OnStart() and Session_OnEnd(). These events are accessed in the global.asa. You can see an example of global.asa in lesson 10.

What's Next:

We've seen in the last two lessons that Apartment Model Behavior is strictly forbidden in the Application Intrinsic Object. (It's not forbidden in the Session Object, but it is restricted.) So how do we store values (functions in particular) for reuse in many scripts? That is the subject of Lesson 13.


------------------------------- 13 -----------------------------------

nclude Files

Server Side Includes:

Experienced JavaScript programmers know that code reuse is good. Experienced JavaScript programmers also know that JavaScript functions are data types.

So, we should be able to store a JavaScript function inside a Session Variable or an Application Variable, right? Unfortunately, no. The way to reuse JavaScript functions across many pages is to use SSI: Server Side Includes.

<%@LANGUAGE="JavaScript"%>


ASP JavaScript Lessons(8-14)-speakitnow-ChinaUnix博客
  • 博客访问: 5547957
  • 博文数量: 915
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 5216
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-15 17:17
文章分类

全部博文(915)

文章存档

2011年(1)

2008年(134)

2007年(287)

2006年(493)

我的朋友
微信关注

IT168企业级官微



微信号:IT168qiye



系统架构师大会



微信号:SACC2013

订阅
热词专题
ASP JavaScript Lessons(8-14) 2006-12-31 14:48:22

分类: Java

-------------------------------- 8 -----------------------------------

The Request Object

Request Object:

Request has five (5) Collections, one (1) Property, and one (1) Method. You'll use the Collections far more than the property or the method.

Request Collections:

Below is a table of the Request Collections and descriptions of how they are used.

Request Collections
ClientCertificateRequest.ClientCertificate("Key[Field]")
Client security info for SSL encryption
CookiesRequest.Cookies("cookieName")
Holds cookie value stored on the client
FormRequest.Form("formName")
Holds value sent via HTML Form
QueryStringRequest.QueryString("keyName")
Name/Value pair appended to the end of the URL
ServerVariablesRequest.ServerVariables("variableName")
Hold values sent in the HTTP Headers

ClientCertificate:

Request.ClientCertificate is used with S.S.L. (Secure Sockets Layer). It is beyond the scope of this web site.

Cookies:

We will learn Request.Cookies and Response.Cookies together in Lesson 08. Please be patient.

Form:

Request.Form is probably the workhorse of the Request Collections. The first script is a repeat from Lesson 03.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

Type something into the text box and submit it.



How Much Money do you make each month?






Click Here to run script08.asp in a new window. It posts information to script08a.asp which is found below. In turn, script08a.asp posts information to script08b.asp which is also found below.

<%@LANGUAGE="JavaScript"%>
<%
var WebPageVariable = new String( Request.Form("WebPageVariable") )
WebPageVariable = WebPageVariable.toUpperCase();

var monthlySalary = new String( Request.Form("monthlySalary") )
monthlySalary = monthlySalary.toLowerCase();
%>

The Web Page Variable you typed is: <%=WebPageVariable%>

The monthly salary you listed is: <%=monthlySalary%>



Click the button to see Query Strings




We'll be using Request.Form when we "Post" an HTML form to the server. Notice that the NAME attribute in the HTML form corresponds to the "name" in Request.Form("name"). To be more specific, corresponds with Request.Form("WebPageVariable"). We already talked about the need for the new String( ) constructor back in Lesson 03.

QueryString:

We'll be using Request.QueryString when we use an HTML form to "Get" a page from the server. Request.QueryString() is very similar to Request.Form(). Take a look at script08b.asp which I printed below.

<%@LANGUAGE="JavaScript"%>
<%
var QueryVariable = new String( Request.QueryString("QueryVariable") )
%>

The QueryString Value is: <%=QueryVariable%>

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>
Click Here
for the link to script08b.asp?QueryVariable=<%=QueryVariable%>
<%
} //closing bracket for if statement.
%>

If you haven't already, Click Here to run script08.asp in a new window. Cycle through all the forms and links, and then come back.

You can use Request.QueryString in two different ways. You can either use an HTML form to "Get" a page from the server, which will generate a query string. Or you can manually build a query string and add it to the backside of a link. We'll dissect script08b.asp from top to bottom.

var QueryVariable = new String( Request.QueryString("QueryVariable") )

The line above in script08b.asp corresponds to the line below from script08a.asp


The NAME="someName" in the HTML form becomes the Request.QueryString("someName") on the next page.

About half way into script08b.asp are the lines I reprinted below.

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>

We've already converted Request.QueryString() into a JavaScript string at the top of the script. So, now we can do a string comparison.

If the QueryVariable hasn't already been set equal to "Lesson 08's new Query!" then we do that. Then we use the escape( ) method to convert white space and special characters into Unicode. (URL's should contain neither whitespace, nor most special characters.)

In lesson 14 we'll see a better way to encode URL's. When we study the Server Object, we'll see Server.URLEncode(). But for now, just know that escape() works.

You can have more than one QueryString on each page. If you lose count of your QueryStrings, then you use Request.QueryString.Count to tell you the number.

The Request Shortcut:

Request.Form() and Request.QueryString() share a shortcut. Request.Form("WebPageVariable") can be abbreviated as Request("WebPageVariable") and Request.QueryString("QueryVariable") can be abbreviated as Request("QueryVariable").

ServerVariables:

Server Variables represent the HTTP Headers sent to the server by the client. I won't demonstrate them all, because there are too many.

<%@LANGUAGE="JavaScript"%>










ALL_RAW<%=Request.ServerVariables("ALL_RAW")%>
REMOTE_ADDR<%=Request.ServerVariables("REMOTE_ADDR")%>
HTTP_USER_AGENT<%=Request.ServerVariables("HTTP_USER_AGENT")%>
URL<%=Request.ServerVariables("URL")%>


Click Here to run the script in a new window.

Demonstrated above are four (4) server variables. There are (give or take) about 50 server variables available. You can look up the full list of server variables for yourself on the internet.

Misc. Notes:

Request.BinaryRead() is the lone method and TotalBytes is the lone property. Request.BinaryRead(Request.TotalBytes) retrieves data from an HTML form using "POST." You must supply the TotalBytes as an argument. It stores the data into an array. BinaryRead cannot be used at the same time as Request.Form().

Next Stop, Cookies:

The only Request Collection I did not cover was Cookies. I want to cover Request.Cookies and Response.Cookies side by side. So we'll do that in Lesson 09.


-------------------------------- 9 -----------------------------------

ookies and Cookies

Response Cookies in General:

We'll start with the Response Cookies collection. I don't think it could be any easier. You simply put the name of the cookie in the argument. The corresponding value is a string. The only time it gets complicated is when you use keys (which I demonstrate below).

<%@LANGUAGE="JavaScript"%>
<%
var Tomorrow=new Date()
Tomorrow.setDate(Tomorrow.getDate() + 1)
myExpire = (Tomorrow.getMonth() + 1) + "/" + Tomorrow.getDate()
myExpire += "/" + Tomorrow.getFullYear()

Response.Cookies("firstCookie") = "I like cookies."
Response.Cookies("firstCookie").Expires=myExpire

Response.Cookies("secondCookie") = "ASP Cookies Are Easy."
Response.Cookies("secondCookie").Expires=myExpire

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."
Response.Cookies("thirdCookie").Expires=myExpire
%>


We're just setting <%=Response.Cookies.Count%> cookies.

Click Here to retrieve these cookies.

Click Here to run the script in a new window.

Setting a cookie with ASP is pretty simple. The format is Response.Cookies("name")="value". That "value" can be either a JavaScript string or an ASP native type such as Request.Form("userEmail").

Response Cookie Keys:

If on the first page of your ASP application Response.Cookies("myOnlyCookie") is set, and subsequently on page two of your application Response.Cookies("myOnlyCookie") is reassigned a second value, then only the second value will remain. The first value is lost in this circumstance.

The solution is to either use multiple cookies or to use multiple Keys in the SAME cookie.

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."

The Setting of one or more Keys is pretty simple. It follows this format: Response.Cookies("name")("key")="value". Again, the "value" can either be a JavaScript string or ASP native type. The advantage of using keys is that you can store multiple Key/Value pairs inside the very same cookie.

Request Cookies:

Generally you will find ASP cookie management to be far easier than Client Side JavaScript cookies. Down below is the script that retrieves the cookies.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
var firstCookie = Request.Cookies("firstCookie");
var secondCookie = Request.Cookies("secondCookie");
var thirdCookie2Keys = Request.Cookies("thirdCookie")("firstKey")
thirdCookie2Keys += " " + Request.Cookies("thirdCookie")("secondKey");
%>

There are <%=Request.Cookies.Count%> Cookies.

1) <%=firstCookie%>

2) <%=secondCookie%>

3) <%=thirdCookie2Keys%>

Click Here to see how we would sort cookies
if we didn't know their names.

Click Here to run the script in a new window.

Do I even need to explain "firstCookie" and "secondCookie"? It's so easy. However, I will have to have explain the retrieval of Keys in "thirdCookie".

We retrieve cookies in almost exactly the same way that we set them, and that goes for Keys as well. If you keep track of your Key names, then retrieving their values is pretty easy.

var thirdCookieFirstKey = Request.Cookies("thirdCookie")("firstKey")

Deleting Cookies:

To delete a cookie, give it an expiration date in the past. The following is not in our examples, but it would work.

var Yesterday=new Date()
Yesterday.setDate(Yesterday.getDate() - 1)
myExpire = (Yesterday.getMonth() + 1) + "/" + Yesterday.getDate()
myExpire += "/" + Yesterday.getFullYear()
Response.Cookies("firstCookie").Expires=myExpire

Cookie Crumbs:

What if you lose track of your cookie names? What if you lose your Keys? First of all, don't do that. But secondly, we have options.

We can use a VBScript Function with a for/each loop. We can use Javascript's new Enumerator( ) or we can use a pair of for Loops. We, however, cannot use JavaScript's for/in loop. This means we have to be creative.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
%>


<%
Response.Write("Let's use a VBScript function to ")
Response.Write("sort out the Cookies and Keys.

\r")
var longCookie = forEachCookie()
if (longCookie)
{
longCookie = longCookie.split("; ")
for (i=0;i<=longCookie.length-1;i++)
{
Response.Write(longCookie[ i ] + "
\r")
}
}
Response.Write("
\r")

Response.Write("Let's use new Enumerator( ) to ")
Response.Write("sort out the Cookies and Keys.

\r")
var myEnum = new Enumerator(Request.Cookies);
for (myEnum; !myEnum.atEnd() ; myEnum.moveNext() )
{
Response.Write(myEnum.item() + "=")
n=Request.Cookies(myEnum.item()).Count
if (n)
{
for (o=1;o<=n;o++)
{
Response.Write(Request.Cookies(myEnum.item())(o) + " ")
}
//Begin alternate method of using Enumerator()
Response.Write("
\rOR... ")
Response.Write(myEnum.item() + "=")
Response.Write(unescape(Request.Cookies(myEnum.item())))
//End alternate method
}
else
{
Response.Write(Request.Cookies(myEnum.item()))
}
Response.Write("
\r")
}
Response.Write("
\r")

Response.Write("Let's use a pair of JavaScript loops to ")
Response.Write("sort out the Cookies and Keys.

\r")
a=Request.Cookies.Count
for (b=1;b<=a;b++)
{
d = Request.Cookies(b).Count
if (d)
{
for (c=1;c<=d;c++)
{
Response.Write(Request.Cookies(b)(c) + " ")
}
Response.Write("
\r")
}
else
{
Response.Write(Request.Cookies(b) + "
\r")
}
}
%>

Click Here to run the script in a new window.

We do the same job three times. You decide for yourself which one you like best. In the first example you can plainly see from the script, I ask a VBScript function to find and break down all the cookies. I then output the data back to the waiting JavaScript variable.

var longCookie = forEachCookie()

What can I say? Don't lose track of your cookies and don't lose track of your Keys. Otherwise you might have to get a VBScript slim jim.

The new Enumerator() is okay. I use Enumerator two different ways; one way fails to capture the Key names, and the other way successfully captures the key names (but it needs unescape() to get the Key values to print normally).

In round three, I use a pair of for loops, but they're not as functional as for/in would be. (Notice the lack of Key names.)

Misc. Notes:

We didn't use new String( ) in this lesson. But remember, if you want to manipulate the cookie values inside JavaScript functions or methods, then you will need new String().

var firstCookie = new String(Request.Cookies("firstCookie") )
firstCookie = firstCookie.toUpperCase()

Also, if you were to use Client Side scripting to locate cookies, you would have noticed that there is an extra cookie. ASP keeps track of its sessions using a cookie.



------------------------------- 10 -----------------------------------

lobal ASA

Global.asa:

First of all, what is a global.asa? It's an optional script file that holds certain "global" information that you can access through the entire ASP appliciation. The global.asa is a plain text file saved with the .asa extension.

You should only have one global.asa and it should go in your top level directory.

Below is an example global.asa file. Don't try to understand the script just yet. We'll get to the specifics in the next two lessons.







List of Can Do's:

There are four things you can do with a global.asa.

1) Object Declarations
2) Application Events
3) Session Events
4) Library Reference.

I don't expect you understand any of that yet. Just remember, there are only a few things we can do with the global.asa. Let's move on to lesson 11.



------------------------------- 11 -----------------------------------

pplication Object

Overview:

The Application Object represents a collection of ASP pages. The Application object has zero (0) properties, two (2) collections, two (2) methods, and two (2) events.

Get Started:

Below are a couple scripts for lesson11.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>


Would you like to chose the official Application color?





No, click here.

Click Here to run script11.asp in a new window. Below is script11a.asp.

<%@LANGUAGE="JavaScript"%>

<%
Application.Lock()
var OfficialColor = new String( Request.Form("OfficialColor") )
if (OfficialColor=="red")
{
Application("OfficialColor") = "red"
}
if (OfficialColor=="white")
{
Application("OfficialColor") = "white"
}
if (OfficialColor=="blue")
{
Application("OfficialColor") = "blue"
}
if (OfficialColor=="undefined")
{
//Do nothing. Just leave the color alone.
}
Application.Unlock()
%>
">

The official application color is <%=Application("OfficialColor")%>.




Application Collections:

The two collections are Contents and StaticObjects. StaticObjects come in the form of the flag. That's done in the global.asa that we saw in Lesson 09. I'll demonstrate it again down below.

By contrast, the Contents collection is demonstrated above. It allows you to set and retrieve variables with Application scope. The format for setting an Application variable is Application.Contents("VariableName")="VariableValue". However, since Contents is the default Collection, we have a little shortcut for setting Application variables. The shortcut goes like this: Application("VariableName")="VariableValue".

Share the Variable:

One last thought on Application Variables. The application variable is shared by all visitors. Let's say that you and I are on the same ASP web site at the same time. If you set the background color to white in script11.asp, then I will see "white" as the official color if I go directly to script11a.asp. Application Variables are by no means the most efficient means of passing information from one user to another.

No Apartment Model:

You may notice that the example above seems to be inefficient. Why not just directly assign Application("OfficialColor") = Request.Form("OfficialColor")? Because we can't. By design, the newer (and updated) versions of Microsoft server software intentionally do not support Apartment Model Behavior.

Application Methods:

The two Application Methods are Lock() and Unlock(). Lock() blocks all other users from changing the Application variables. Unlock() releases control so that other users can change it. That's important on a larger site where multiple users may be trying to access the same page at the same time.

Application Events:

The two Application events are Application_OnStart() and Application_OnEnd(). These events are accessed in the global.asa. Let's repeat that script from lesson 09.







Misc. Items:

Application.Contents has two methods of its own. Application.Contents.Remove("VariableName") and Application.Contents.RemoveAll().

You'll notice there are also Session Events in the global.asa. We'll deal with those in Lesson 12. You'll also notice a call to the ADO Library. We'll talk about that when we get to databases.


------------------------------- 12 -----------------------------------

ession Object

Overview:

The Session Object is how you track a single user across many pages. It has four (4) properties, two (2) collections, one (1) method, and two (2) events.

Get Started:

In this series of examples we will create a password system. We will use the Session Object to track whether or not a user is authorized to view certain pages. Below are several scripts for lesson12. Look at them, play with, and then read the explanations that come further down the page.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

To play along with our password page, put in a user name and a password.


The correct user name is guest.

And the correct password is also guest.


User:

Pass:





Click Here to run script12.asp in a new window. Below is script12a.asp.

<%@LANGUAGE="JavaScript"%>
<%
var userName=new String(Request.Form("userName"))
var userPassword=new String(Request.Form("userPassword"))
if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}
else
{
Session("Authorized")=false
%>

You did not supply the correct Name & Password.

Click here to log in.

<%
} //end else statement
%>

We'll skip over script12b.asp entirely because it's almost exactly the same as script12c.asp. Down below is script12c.asp.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
%>

The second of two pages that are password protected.

Click Here to log out.

<%
} //end of else statement
%>

Above is script12c.asp, which is the second of two password-protected pages. Below is script12.asp, which is the logout page.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
var SessionID=Session.SessionID
Session.Abandon()
%>

You have sucessfully logged out.

This was session <%=SessionID%>.


Now try a link to one of the
pages you've already visited.


script12b.asp

script12c.asp

script12d.asp


<%
} //end of else statement
%>

A Quick Explanation:

After all that, the last thing you want to see is another grey box full of code. Sorry to do it one more time but, the keystone to this system is in script12a.asp. I've reprinted it down below.

if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}

Any page can now be turned into a password protected page with the following line: if (Session("Authorized")!=true). Session Variables are part of the Session Collections. Let's talk about them.

Session Collections:

The two Session Collections are Session.Contents and Session.StaticObjects. They parallel the Application.Contents and Application.StaticObjects.

Using Session.Contents("someVariable")="someValue" we can set Session Variables. These variables allow us to carry values from one page to the next. Since Contents is the default collection we can use a little shortcut. It goes like this: Session("someVariable")="someValue".

The shortcut is what you saw in the scripts above.

Session.Contents has two methods of its own. They are Session.Contents.Remove("variableName") and Session.Contents.RemoveAll().

We did not demonstrate StaticObjects in the scripts above. It comes in the form of the flag (set for Session scope).

No Sharing:

Remember how Application variables could be shared by all viewers on your ASP web site? That's not so with Session Variables. They are private; Session Variables are to be accessed only by one user.

Session.Abandon( ):

My bet is you could figure out Session.Abandon() without any explanation. However, let me just state for the record that Session.Abandon() ends the user's session and releases the Session Variables from memory.

Session Properties:

Let's briefly discuss two properties you are not likely to use. Session.CodePage lets you call for foreign character sets, like Chinese or Russian. Session.LCID is a location identifier. It determines the time zone and language for the server. Don't mess with it.

Now let's move on to something you might actually use from time to time. Session.SessionID is a read-only property generated by the server, and assigned to one specific user during one specific session. The SessionID follows the user from the beginning of the session until the end.

Session.Timeout is the number of minutes that a user can be idle before the Server ends the user's individual session and reclaims the memory that was allocated to Session Variables. (Session.Timeout is demonstrated in the global.asa in lesson 10.)

Session Events:

The two Session events are Session_OnStart() and Session_OnEnd(). These events are accessed in the global.asa. You can see an example of global.asa in lesson 10.

What's Next:

We've seen in the last two lessons that Apartment Model Behavior is strictly forbidden in the Application Intrinsic Object. (It's not forbidden in the Session Object, but it is restricted.) So how do we store values (functions in particular) for reuse in many scripts? That is the subject of Lesson 13.


------------------------------- 13 -----------------------------------

nclude Files

Server Side Includes:

Experienced JavaScript programmers know that code reuse is good. Experienced JavaScript programmers also know that JavaScript functions are data types.

So, we should be able to store a JavaScript function inside a Session Variable or an Application Variable, right? Unfortunately, no. The way to reuse JavaScript functions across many pages is to use SSI: Server Side Includes.

<%@LANGUAGE="JavaScript"%>


ASP JavaScript Lessons(8-14)-speakitnow-ChinaUnix博客
  • 博客访问: 5547958
  • 博文数量: 915
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 5216
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-15 17:17
文章分类

全部博文(915)

文章存档

2011年(1)

2008年(134)

2007年(287)

2006年(493)

我的朋友
微信关注

IT168企业级官微



微信号:IT168qiye



系统架构师大会



微信号:SACC2013

订阅
热词专题
ASP JavaScript Lessons(8-14) 2006-12-31 14:48:22

分类: Java

-------------------------------- 8 -----------------------------------

The Request Object

Request Object:

Request has five (5) Collections, one (1) Property, and one (1) Method. You'll use the Collections far more than the property or the method.

Request Collections:

Below is a table of the Request Collections and descriptions of how they are used.

Request Collections
ClientCertificateRequest.ClientCertificate("Key[Field]")
Client security info for SSL encryption
CookiesRequest.Cookies("cookieName")
Holds cookie value stored on the client
FormRequest.Form("formName")
Holds value sent via HTML Form
QueryStringRequest.QueryString("keyName")
Name/Value pair appended to the end of the URL
ServerVariablesRequest.ServerVariables("variableName")
Hold values sent in the HTTP Headers

ClientCertificate:

Request.ClientCertificate is used with S.S.L. (Secure Sockets Layer). It is beyond the scope of this web site.

Cookies:

We will learn Request.Cookies and Response.Cookies together in Lesson 08. Please be patient.

Form:

Request.Form is probably the workhorse of the Request Collections. The first script is a repeat from Lesson 03.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

Type something into the text box and submit it.



How Much Money do you make each month?






Click Here to run script08.asp in a new window. It posts information to script08a.asp which is found below. In turn, script08a.asp posts information to script08b.asp which is also found below.

<%@LANGUAGE="JavaScript"%>
<%
var WebPageVariable = new String( Request.Form("WebPageVariable") )
WebPageVariable = WebPageVariable.toUpperCase();

var monthlySalary = new String( Request.Form("monthlySalary") )
monthlySalary = monthlySalary.toLowerCase();
%>

The Web Page Variable you typed is: <%=WebPageVariable%>

The monthly salary you listed is: <%=monthlySalary%>



Click the button to see Query Strings




We'll be using Request.Form when we "Post" an HTML form to the server. Notice that the NAME attribute in the HTML form corresponds to the "name" in Request.Form("name"). To be more specific, corresponds with Request.Form("WebPageVariable"). We already talked about the need for the new String( ) constructor back in Lesson 03.

QueryString:

We'll be using Request.QueryString when we use an HTML form to "Get" a page from the server. Request.QueryString() is very similar to Request.Form(). Take a look at script08b.asp which I printed below.

<%@LANGUAGE="JavaScript"%>
<%
var QueryVariable = new String( Request.QueryString("QueryVariable") )
%>

The QueryString Value is: <%=QueryVariable%>

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>
Click Here
for the link to script08b.asp?QueryVariable=<%=QueryVariable%>
<%
} //closing bracket for if statement.
%>

If you haven't already, Click Here to run script08.asp in a new window. Cycle through all the forms and links, and then come back.

You can use Request.QueryString in two different ways. You can either use an HTML form to "Get" a page from the server, which will generate a query string. Or you can manually build a query string and add it to the backside of a link. We'll dissect script08b.asp from top to bottom.

var QueryVariable = new String( Request.QueryString("QueryVariable") )

The line above in script08b.asp corresponds to the line below from script08a.asp


The NAME="someName" in the HTML form becomes the Request.QueryString("someName") on the next page.

About half way into script08b.asp are the lines I reprinted below.

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>

We've already converted Request.QueryString() into a JavaScript string at the top of the script. So, now we can do a string comparison.

If the QueryVariable hasn't already been set equal to "Lesson 08's new Query!" then we do that. Then we use the escape( ) method to convert white space and special characters into Unicode. (URL's should contain neither whitespace, nor most special characters.)

In lesson 14 we'll see a better way to encode URL's. When we study the Server Object, we'll see Server.URLEncode(). But for now, just know that escape() works.

You can have more than one QueryString on each page. If you lose count of your QueryStrings, then you use Request.QueryString.Count to tell you the number.

The Request Shortcut:

Request.Form() and Request.QueryString() share a shortcut. Request.Form("WebPageVariable") can be abbreviated as Request("WebPageVariable") and Request.QueryString("QueryVariable") can be abbreviated as Request("QueryVariable").

ServerVariables:

Server Variables represent the HTTP Headers sent to the server by the client. I won't demonstrate them all, because there are too many.

<%@LANGUAGE="JavaScript"%>










ALL_RAW<%=Request.ServerVariables("ALL_RAW")%>
REMOTE_ADDR<%=Request.ServerVariables("REMOTE_ADDR")%>
HTTP_USER_AGENT<%=Request.ServerVariables("HTTP_USER_AGENT")%>
URL<%=Request.ServerVariables("URL")%>


Click Here to run the script in a new window.

Demonstrated above are four (4) server variables. There are (give or take) about 50 server variables available. You can look up the full list of server variables for yourself on the internet.

Misc. Notes:

Request.BinaryRead() is the lone method and TotalBytes is the lone property. Request.BinaryRead(Request.TotalBytes) retrieves data from an HTML form using "POST." You must supply the TotalBytes as an argument. It stores the data into an array. BinaryRead cannot be used at the same time as Request.Form().

Next Stop, Cookies:

The only Request Collection I did not cover was Cookies. I want to cover Request.Cookies and Response.Cookies side by side. So we'll do that in Lesson 09.


-------------------------------- 9 -----------------------------------

ookies and Cookies

Response Cookies in General:

We'll start with the Response Cookies collection. I don't think it could be any easier. You simply put the name of the cookie in the argument. The corresponding value is a string. The only time it gets complicated is when you use keys (which I demonstrate below).

<%@LANGUAGE="JavaScript"%>
<%
var Tomorrow=new Date()
Tomorrow.setDate(Tomorrow.getDate() + 1)
myExpire = (Tomorrow.getMonth() + 1) + "/" + Tomorrow.getDate()
myExpire += "/" + Tomorrow.getFullYear()

Response.Cookies("firstCookie") = "I like cookies."
Response.Cookies("firstCookie").Expires=myExpire

Response.Cookies("secondCookie") = "ASP Cookies Are Easy."
Response.Cookies("secondCookie").Expires=myExpire

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."
Response.Cookies("thirdCookie").Expires=myExpire
%>


We're just setting <%=Response.Cookies.Count%> cookies.

Click Here to retrieve these cookies.

Click Here to run the script in a new window.

Setting a cookie with ASP is pretty simple. The format is Response.Cookies("name")="value". That "value" can be either a JavaScript string or an ASP native type such as Request.Form("userEmail").

Response Cookie Keys:

If on the first page of your ASP application Response.Cookies("myOnlyCookie") is set, and subsequently on page two of your application Response.Cookies("myOnlyCookie") is reassigned a second value, then only the second value will remain. The first value is lost in this circumstance.

The solution is to either use multiple cookies or to use multiple Keys in the SAME cookie.

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."

The Setting of one or more Keys is pretty simple. It follows this format: Response.Cookies("name")("key")="value". Again, the "value" can either be a JavaScript string or ASP native type. The advantage of using keys is that you can store multiple Key/Value pairs inside the very same cookie.

Request Cookies:

Generally you will find ASP cookie management to be far easier than Client Side JavaScript cookies. Down below is the script that retrieves the cookies.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
var firstCookie = Request.Cookies("firstCookie");
var secondCookie = Request.Cookies("secondCookie");
var thirdCookie2Keys = Request.Cookies("thirdCookie")("firstKey")
thirdCookie2Keys += " " + Request.Cookies("thirdCookie")("secondKey");
%>

There are <%=Request.Cookies.Count%> Cookies.

1) <%=firstCookie%>

2) <%=secondCookie%>

3) <%=thirdCookie2Keys%>

Click Here to see how we would sort cookies
if we didn't know their names.

Click Here to run the script in a new window.

Do I even need to explain "firstCookie" and "secondCookie"? It's so easy. However, I will have to have explain the retrieval of Keys in "thirdCookie".

We retrieve cookies in almost exactly the same way that we set them, and that goes for Keys as well. If you keep track of your Key names, then retrieving their values is pretty easy.

var thirdCookieFirstKey = Request.Cookies("thirdCookie")("firstKey")

Deleting Cookies:

To delete a cookie, give it an expiration date in the past. The following is not in our examples, but it would work.

var Yesterday=new Date()
Yesterday.setDate(Yesterday.getDate() - 1)
myExpire = (Yesterday.getMonth() + 1) + "/" + Yesterday.getDate()
myExpire += "/" + Yesterday.getFullYear()
Response.Cookies("firstCookie").Expires=myExpire

Cookie Crumbs:

What if you lose track of your cookie names? What if you lose your Keys? First of all, don't do that. But secondly, we have options.

We can use a VBScript Function with a for/each loop. We can use Javascript's new Enumerator( ) or we can use a pair of for Loops. We, however, cannot use JavaScript's for/in loop. This means we have to be creative.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
%>


<%
Response.Write("Let's use a VBScript function to ")
Response.Write("sort out the Cookies and Keys.

\r")
var longCookie = forEachCookie()
if (longCookie)
{
longCookie = longCookie.split("; ")
for (i=0;i<=longCookie.length-1;i++)
{
Response.Write(longCookie[ i ] + "
\r")
}
}
Response.Write("
\r")

Response.Write("Let's use new Enumerator( ) to ")
Response.Write("sort out the Cookies and Keys.

\r")
var myEnum = new Enumerator(Request.Cookies);
for (myEnum; !myEnum.atEnd() ; myEnum.moveNext() )
{
Response.Write(myEnum.item() + "=")
n=Request.Cookies(myEnum.item()).Count
if (n)
{
for (o=1;o<=n;o++)
{
Response.Write(Request.Cookies(myEnum.item())(o) + " ")
}
//Begin alternate method of using Enumerator()
Response.Write("
\rOR... ")
Response.Write(myEnum.item() + "=")
Response.Write(unescape(Request.Cookies(myEnum.item())))
//End alternate method
}
else
{
Response.Write(Request.Cookies(myEnum.item()))
}
Response.Write("
\r")
}
Response.Write("
\r")

Response.Write("Let's use a pair of JavaScript loops to ")
Response.Write("sort out the Cookies and Keys.

\r")
a=Request.Cookies.Count
for (b=1;b<=a;b++)
{
d = Request.Cookies(b).Count
if (d)
{
for (c=1;c<=d;c++)
{
Response.Write(Request.Cookies(b)(c) + " ")
}
Response.Write("
\r")
}
else
{
Response.Write(Request.Cookies(b) + "
\r")
}
}
%>

Click Here to run the script in a new window.

We do the same job three times. You decide for yourself which one you like best. In the first example you can plainly see from the script, I ask a VBScript function to find and break down all the cookies. I then output the data back to the waiting JavaScript variable.

var longCookie = forEachCookie()

What can I say? Don't lose track of your cookies and don't lose track of your Keys. Otherwise you might have to get a VBScript slim jim.

The new Enumerator() is okay. I use Enumerator two different ways; one way fails to capture the Key names, and the other way successfully captures the key names (but it needs unescape() to get the Key values to print normally).

In round three, I use a pair of for loops, but they're not as functional as for/in would be. (Notice the lack of Key names.)

Misc. Notes:

We didn't use new String( ) in this lesson. But remember, if you want to manipulate the cookie values inside JavaScript functions or methods, then you will need new String().

var firstCookie = new String(Request.Cookies("firstCookie") )
firstCookie = firstCookie.toUpperCase()

Also, if you were to use Client Side scripting to locate cookies, you would have noticed that there is an extra cookie. ASP keeps track of its sessions using a cookie.



------------------------------- 10 -----------------------------------

lobal ASA

Global.asa:

First of all, what is a global.asa? It's an optional script file that holds certain "global" information that you can access through the entire ASP appliciation. The global.asa is a plain text file saved with the .asa extension.

You should only have one global.asa and it should go in your top level directory.

Below is an example global.asa file. Don't try to understand the script just yet. We'll get to the specifics in the next two lessons.







List of Can Do's:

There are four things you can do with a global.asa.

1) Object Declarations
2) Application Events
3) Session Events
4) Library Reference.

I don't expect you understand any of that yet. Just remember, there are only a few things we can do with the global.asa. Let's move on to lesson 11.



------------------------------- 11 -----------------------------------

pplication Object

Overview:

The Application Object represents a collection of ASP pages. The Application object has zero (0) properties, two (2) collections, two (2) methods, and two (2) events.

Get Started:

Below are a couple scripts for lesson11.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>


Would you like to chose the official Application color?





No, click here.

Click Here to run script11.asp in a new window. Below is script11a.asp.

<%@LANGUAGE="JavaScript"%>

<%
Application.Lock()
var OfficialColor = new String( Request.Form("OfficialColor") )
if (OfficialColor=="red")
{
Application("OfficialColor") = "red"
}
if (OfficialColor=="white")
{
Application("OfficialColor") = "white"
}
if (OfficialColor=="blue")
{
Application("OfficialColor") = "blue"
}
if (OfficialColor=="undefined")
{
//Do nothing. Just leave the color alone.
}
Application.Unlock()
%>
">

The official application color is <%=Application("OfficialColor")%>.




Application Collections:

The two collections are Contents and StaticObjects. StaticObjects come in the form of the flag. That's done in the global.asa that we saw in Lesson 09. I'll demonstrate it again down below.

By contrast, the Contents collection is demonstrated above. It allows you to set and retrieve variables with Application scope. The format for setting an Application variable is Application.Contents("VariableName")="VariableValue". However, since Contents is the default Collection, we have a little shortcut for setting Application variables. The shortcut goes like this: Application("VariableName")="VariableValue".

Share the Variable:

One last thought on Application Variables. The application variable is shared by all visitors. Let's say that you and I are on the same ASP web site at the same time. If you set the background color to white in script11.asp, then I will see "white" as the official color if I go directly to script11a.asp. Application Variables are by no means the most efficient means of passing information from one user to another.

No Apartment Model:

You may notice that the example above seems to be inefficient. Why not just directly assign Application("OfficialColor") = Request.Form("OfficialColor")? Because we can't. By design, the newer (and updated) versions of Microsoft server software intentionally do not support Apartment Model Behavior.

Application Methods:

The two Application Methods are Lock() and Unlock(). Lock() blocks all other users from changing the Application variables. Unlock() releases control so that other users can change it. That's important on a larger site where multiple users may be trying to access the same page at the same time.

Application Events:

The two Application events are Application_OnStart() and Application_OnEnd(). These events are accessed in the global.asa. Let's repeat that script from lesson 09.







Misc. Items:

Application.Contents has two methods of its own. Application.Contents.Remove("VariableName") and Application.Contents.RemoveAll().

You'll notice there are also Session Events in the global.asa. We'll deal with those in Lesson 12. You'll also notice a call to the ADO Library. We'll talk about that when we get to databases.


------------------------------- 12 -----------------------------------

ession Object

Overview:

The Session Object is how you track a single user across many pages. It has four (4) properties, two (2) collections, one (1) method, and two (2) events.

Get Started:

In this series of examples we will create a password system. We will use the Session Object to track whether or not a user is authorized to view certain pages. Below are several scripts for lesson12. Look at them, play with, and then read the explanations that come further down the page.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

To play along with our password page, put in a user name and a password.


The correct user name is guest.

And the correct password is also guest.


User:

Pass:





Click Here to run script12.asp in a new window. Below is script12a.asp.

<%@LANGUAGE="JavaScript"%>
<%
var userName=new String(Request.Form("userName"))
var userPassword=new String(Request.Form("userPassword"))
if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}
else
{
Session("Authorized")=false
%>

You did not supply the correct Name & Password.

Click here to log in.

<%
} //end else statement
%>

We'll skip over script12b.asp entirely because it's almost exactly the same as script12c.asp. Down below is script12c.asp.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
%>

The second of two pages that are password protected.

Click Here to log out.

<%
} //end of else statement
%>

Above is script12c.asp, which is the second of two password-protected pages. Below is script12.asp, which is the logout page.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
var SessionID=Session.SessionID
Session.Abandon()
%>

You have sucessfully logged out.

This was session <%=SessionID%>.


Now try a link to one of the
pages you've already visited.


script12b.asp

script12c.asp

script12d.asp


<%
} //end of else statement
%>

A Quick Explanation:

After all that, the last thing you want to see is another grey box full of code. Sorry to do it one more time but, the keystone to this system is in script12a.asp. I've reprinted it down below.

if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}

Any page can now be turned into a password protected page with the following line: if (Session("Authorized")!=true). Session Variables are part of the Session Collections. Let's talk about them.

Session Collections:

The two Session Collections are Session.Contents and Session.StaticObjects. They parallel the Application.Contents and Application.StaticObjects.

Using Session.Contents("someVariable")="someValue" we can set Session Variables. These variables allow us to carry values from one page to the next. Since Contents is the default collection we can use a little shortcut. It goes like this: Session("someVariable")="someValue".

The shortcut is what you saw in the scripts above.

Session.Contents has two methods of its own. They are Session.Contents.Remove("variableName") and Session.Contents.RemoveAll().

We did not demonstrate StaticObjects in the scripts above. It comes in the form of the flag (set for Session scope).

No Sharing:

Remember how Application variables could be shared by all viewers on your ASP web site? That's not so with Session Variables. They are private; Session Variables are to be accessed only by one user.

Session.Abandon( ):

My bet is you could figure out Session.Abandon() without any explanation. However, let me just state for the record that Session.Abandon() ends the user's session and releases the Session Variables from memory.

Session Properties:

Let's briefly discuss two properties you are not likely to use. Session.CodePage lets you call for foreign character sets, like Chinese or Russian. Session.LCID is a location identifier. It determines the time zone and language for the server. Don't mess with it.

Now let's move on to something you might actually use from time to time. Session.SessionID is a read-only property generated by the server, and assigned to one specific user during one specific session. The SessionID follows the user from the beginning of the session until the end.

Session.Timeout is the number of minutes that a user can be idle before the Server ends the user's individual session and reclaims the memory that was allocated to Session Variables. (Session.Timeout is demonstrated in the global.asa in lesson 10.)

Session Events:

The two Session events are Session_OnStart() and Session_OnEnd(). These events are accessed in the global.asa. You can see an example of global.asa in lesson 10.

What's Next:

We've seen in the last two lessons that Apartment Model Behavior is strictly forbidden in the Application Intrinsic Object. (It's not forbidden in the Session Object, but it is restricted.) So how do we store values (functions in particular) for reuse in many scripts? That is the subject of Lesson 13.


------------------------------- 13 -----------------------------------

nclude Files

Server Side Includes:

Experienced JavaScript programmers know that code reuse is good. Experienced JavaScript programmers also know that JavaScript functions are data types.

So, we should be able to store a JavaScript function inside a Session Variable or an Application Variable, right? Unfortunately, no. The way to reuse JavaScript functions across many pages is to use SSI: Server Side Includes.

<%@LANGUAGE="JavaScript"%>


ASP JavaScript Lessons(8-14)-speakitnow-ChinaUnix博客
  • 博客访问: 5547959
  • 博文数量: 915
  • 博客积分: 10010
  • 博客等级: 上将
  • 技术积分: 5216
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-15 17:17
文章分类

全部博文(915)

文章存档

2011年(1)

2008年(134)

2007年(287)

2006年(493)

我的朋友
微信关注

IT168企业级官微



微信号:IT168qiye



系统架构师大会



微信号:SACC2013

订阅
热词专题
ASP JavaScript Lessons(8-14) 2006-12-31 14:48:22

分类: Java

-------------------------------- 8 -----------------------------------

The Request Object

Request Object:

Request has five (5) Collections, one (1) Property, and one (1) Method. You'll use the Collections far more than the property or the method.

Request Collections:

Below is a table of the Request Collections and descriptions of how they are used.

Request Collections
ClientCertificateRequest.ClientCertificate("Key[Field]")
Client security info for SSL encryption
CookiesRequest.Cookies("cookieName")
Holds cookie value stored on the client
FormRequest.Form("formName")
Holds value sent via HTML Form
QueryStringRequest.QueryString("keyName")
Name/Value pair appended to the end of the URL
ServerVariablesRequest.ServerVariables("variableName")
Hold values sent in the HTTP Headers

ClientCertificate:

Request.ClientCertificate is used with S.S.L. (Secure Sockets Layer). It is beyond the scope of this web site.

Cookies:

We will learn Request.Cookies and Response.Cookies together in Lesson 08. Please be patient.

Form:

Request.Form is probably the workhorse of the Request Collections. The first script is a repeat from Lesson 03.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

Type something into the text box and submit it.



How Much Money do you make each month?






Click Here to run script08.asp in a new window. It posts information to script08a.asp which is found below. In turn, script08a.asp posts information to script08b.asp which is also found below.

<%@LANGUAGE="JavaScript"%>
<%
var WebPageVariable = new String( Request.Form("WebPageVariable") )
WebPageVariable = WebPageVariable.toUpperCase();

var monthlySalary = new String( Request.Form("monthlySalary") )
monthlySalary = monthlySalary.toLowerCase();
%>

The Web Page Variable you typed is: <%=WebPageVariable%>

The monthly salary you listed is: <%=monthlySalary%>



Click the button to see Query Strings




We'll be using Request.Form when we "Post" an HTML form to the server. Notice that the NAME attribute in the HTML form corresponds to the "name" in Request.Form("name"). To be more specific, corresponds with Request.Form("WebPageVariable"). We already talked about the need for the new String( ) constructor back in Lesson 03.

QueryString:

We'll be using Request.QueryString when we use an HTML form to "Get" a page from the server. Request.QueryString() is very similar to Request.Form(). Take a look at script08b.asp which I printed below.

<%@LANGUAGE="JavaScript"%>
<%
var QueryVariable = new String( Request.QueryString("QueryVariable") )
%>

The QueryString Value is: <%=QueryVariable%>

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>
Click Here
for the link to script08b.asp?QueryVariable=<%=QueryVariable%>
<%
} //closing bracket for if statement.
%>

If you haven't already, Click Here to run script08.asp in a new window. Cycle through all the forms and links, and then come back.

You can use Request.QueryString in two different ways. You can either use an HTML form to "Get" a page from the server, which will generate a query string. Or you can manually build a query string and add it to the backside of a link. We'll dissect script08b.asp from top to bottom.

var QueryVariable = new String( Request.QueryString("QueryVariable") )

The line above in script08b.asp corresponds to the line below from script08a.asp


The NAME="someName" in the HTML form becomes the Request.QueryString("someName") on the next page.

About half way into script08b.asp are the lines I reprinted below.

<%
if (QueryVariable != "Lesson 08's new Query!")
{
QueryVariable="Lesson 08's new Query!"
QueryVariable=escape(QueryVariable)
%>

We've already converted Request.QueryString() into a JavaScript string at the top of the script. So, now we can do a string comparison.

If the QueryVariable hasn't already been set equal to "Lesson 08's new Query!" then we do that. Then we use the escape( ) method to convert white space and special characters into Unicode. (URL's should contain neither whitespace, nor most special characters.)

In lesson 14 we'll see a better way to encode URL's. When we study the Server Object, we'll see Server.URLEncode(). But for now, just know that escape() works.

You can have more than one QueryString on each page. If you lose count of your QueryStrings, then you use Request.QueryString.Count to tell you the number.

The Request Shortcut:

Request.Form() and Request.QueryString() share a shortcut. Request.Form("WebPageVariable") can be abbreviated as Request("WebPageVariable") and Request.QueryString("QueryVariable") can be abbreviated as Request("QueryVariable").

ServerVariables:

Server Variables represent the HTTP Headers sent to the server by the client. I won't demonstrate them all, because there are too many.

<%@LANGUAGE="JavaScript"%>










ALL_RAW<%=Request.ServerVariables("ALL_RAW")%>
REMOTE_ADDR<%=Request.ServerVariables("REMOTE_ADDR")%>
HTTP_USER_AGENT<%=Request.ServerVariables("HTTP_USER_AGENT")%>
URL<%=Request.ServerVariables("URL")%>


Click Here to run the script in a new window.

Demonstrated above are four (4) server variables. There are (give or take) about 50 server variables available. You can look up the full list of server variables for yourself on the internet.

Misc. Notes:

Request.BinaryRead() is the lone method and TotalBytes is the lone property. Request.BinaryRead(Request.TotalBytes) retrieves data from an HTML form using "POST." You must supply the TotalBytes as an argument. It stores the data into an array. BinaryRead cannot be used at the same time as Request.Form().

Next Stop, Cookies:

The only Request Collection I did not cover was Cookies. I want to cover Request.Cookies and Response.Cookies side by side. So we'll do that in Lesson 09.


-------------------------------- 9 -----------------------------------

ookies and Cookies

Response Cookies in General:

We'll start with the Response Cookies collection. I don't think it could be any easier. You simply put the name of the cookie in the argument. The corresponding value is a string. The only time it gets complicated is when you use keys (which I demonstrate below).

<%@LANGUAGE="JavaScript"%>
<%
var Tomorrow=new Date()
Tomorrow.setDate(Tomorrow.getDate() + 1)
myExpire = (Tomorrow.getMonth() + 1) + "/" + Tomorrow.getDate()
myExpire += "/" + Tomorrow.getFullYear()

Response.Cookies("firstCookie") = "I like cookies."
Response.Cookies("firstCookie").Expires=myExpire

Response.Cookies("secondCookie") = "ASP Cookies Are Easy."
Response.Cookies("secondCookie").Expires=myExpire

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."
Response.Cookies("thirdCookie").Expires=myExpire
%>


We're just setting <%=Response.Cookies.Count%> cookies.

Click Here to retrieve these cookies.

Click Here to run the script in a new window.

Setting a cookie with ASP is pretty simple. The format is Response.Cookies("name")="value". That "value" can be either a JavaScript string or an ASP native type such as Request.Form("userEmail").

Response Cookie Keys:

If on the first page of your ASP application Response.Cookies("myOnlyCookie") is set, and subsequently on page two of your application Response.Cookies("myOnlyCookie") is reassigned a second value, then only the second value will remain. The first value is lost in this circumstance.

The solution is to either use multiple cookies or to use multiple Keys in the SAME cookie.

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."

The Setting of one or more Keys is pretty simple. It follows this format: Response.Cookies("name")("key")="value". Again, the "value" can either be a JavaScript string or ASP native type. The advantage of using keys is that you can store multiple Key/Value pairs inside the very same cookie.

Request Cookies:

Generally you will find ASP cookie management to be far easier than Client Side JavaScript cookies. Down below is the script that retrieves the cookies.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
var firstCookie = Request.Cookies("firstCookie");
var secondCookie = Request.Cookies("secondCookie");
var thirdCookie2Keys = Request.Cookies("thirdCookie")("firstKey")
thirdCookie2Keys += " " + Request.Cookies("thirdCookie")("secondKey");
%>

There are <%=Request.Cookies.Count%> Cookies.

1) <%=firstCookie%>

2) <%=secondCookie%>

3) <%=thirdCookie2Keys%>

Click Here to see how we would sort cookies
if we didn't know their names.

Click Here to run the script in a new window.

Do I even need to explain "firstCookie" and "secondCookie"? It's so easy. However, I will have to have explain the retrieval of Keys in "thirdCookie".

We retrieve cookies in almost exactly the same way that we set them, and that goes for Keys as well. If you keep track of your Key names, then retrieving their values is pretty easy.

var thirdCookieFirstKey = Request.Cookies("thirdCookie")("firstKey")

Deleting Cookies:

To delete a cookie, give it an expiration date in the past. The following is not in our examples, but it would work.

var Yesterday=new Date()
Yesterday.setDate(Yesterday.getDate() - 1)
myExpire = (Yesterday.getMonth() + 1) + "/" + Yesterday.getDate()
myExpire += "/" + Yesterday.getFullYear()
Response.Cookies("firstCookie").Expires=myExpire

Cookie Crumbs:

What if you lose track of your cookie names? What if you lose your Keys? First of all, don't do that. But secondly, we have options.

We can use a VBScript Function with a for/each loop. We can use Javascript's new Enumerator( ) or we can use a pair of for Loops. We, however, cannot use JavaScript's for/in loop. This means we have to be creative.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
{
Response.Redirect("script09.asp")
}
%>


<%
Response.Write("Let's use a VBScript function to ")
Response.Write("sort out the Cookies and Keys.

\r")
var longCookie = forEachCookie()
if (longCookie)
{
longCookie = longCookie.split("; ")
for (i=0;i<=longCookie.length-1;i++)
{
Response.Write(longCookie[ i ] + "
\r")
}
}
Response.Write("
\r")

Response.Write("Let's use new Enumerator( ) to ")
Response.Write("sort out the Cookies and Keys.

\r")
var myEnum = new Enumerator(Request.Cookies);
for (myEnum; !myEnum.atEnd() ; myEnum.moveNext() )
{
Response.Write(myEnum.item() + "=")
n=Request.Cookies(myEnum.item()).Count
if (n)
{
for (o=1;o<=n;o++)
{
Response.Write(Request.Cookies(myEnum.item())(o) + " ")
}
//Begin alternate method of using Enumerator()
Response.Write("
\rOR... ")
Response.Write(myEnum.item() + "=")
Response.Write(unescape(Request.Cookies(myEnum.item())))
//End alternate method
}
else
{
Response.Write(Request.Cookies(myEnum.item()))
}
Response.Write("
\r")
}
Response.Write("
\r")

Response.Write("Let's use a pair of JavaScript loops to ")
Response.Write("sort out the Cookies and Keys.

\r")
a=Request.Cookies.Count
for (b=1;b<=a;b++)
{
d = Request.Cookies(b).Count
if (d)
{
for (c=1;c<=d;c++)
{
Response.Write(Request.Cookies(b)(c) + " ")
}
Response.Write("
\r")
}
else
{
Response.Write(Request.Cookies(b) + "
\r")
}
}
%>

Click Here to run the script in a new window.

We do the same job three times. You decide for yourself which one you like best. In the first example you can plainly see from the script, I ask a VBScript function to find and break down all the cookies. I then output the data back to the waiting JavaScript variable.

var longCookie = forEachCookie()

What can I say? Don't lose track of your cookies and don't lose track of your Keys. Otherwise you might have to get a VBScript slim jim.

The new Enumerator() is okay. I use Enumerator two different ways; one way fails to capture the Key names, and the other way successfully captures the key names (but it needs unescape() to get the Key values to print normally).

In round three, I use a pair of for loops, but they're not as functional as for/in would be. (Notice the lack of Key names.)

Misc. Notes:

We didn't use new String( ) in this lesson. But remember, if you want to manipulate the cookie values inside JavaScript functions or methods, then you will need new String().

var firstCookie = new String(Request.Cookies("firstCookie") )
firstCookie = firstCookie.toUpperCase()

Also, if you were to use Client Side scripting to locate cookies, you would have noticed that there is an extra cookie. ASP keeps track of its sessions using a cookie.



------------------------------- 10 -----------------------------------

lobal ASA

Global.asa:

First of all, what is a global.asa? It's an optional script file that holds certain "global" information that you can access through the entire ASP appliciation. The global.asa is a plain text file saved with the .asa extension.

You should only have one global.asa and it should go in your top level directory.

Below is an example global.asa file. Don't try to understand the script just yet. We'll get to the specifics in the next two lessons.







List of Can Do's:

There are four things you can do with a global.asa.

1) Object Declarations
2) Application Events
3) Session Events
4) Library Reference.

I don't expect you understand any of that yet. Just remember, there are only a few things we can do with the global.asa. Let's move on to lesson 11.



------------------------------- 11 -----------------------------------

pplication Object

Overview:

The Application Object represents a collection of ASP pages. The Application object has zero (0) properties, two (2) collections, two (2) methods, and two (2) events.

Get Started:

Below are a couple scripts for lesson11.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>


Would you like to chose the official Application color?





No, click here.

Click Here to run script11.asp in a new window. Below is script11a.asp.

<%@LANGUAGE="JavaScript"%>

<%
Application.Lock()
var OfficialColor = new String( Request.Form("OfficialColor") )
if (OfficialColor=="red")
{
Application("OfficialColor") = "red"
}
if (OfficialColor=="white")
{
Application("OfficialColor") = "white"
}
if (OfficialColor=="blue")
{
Application("OfficialColor") = "blue"
}
if (OfficialColor=="undefined")
{
//Do nothing. Just leave the color alone.
}
Application.Unlock()
%>
">

The official application color is <%=Application("OfficialColor")%>.




Application Collections:

The two collections are Contents and StaticObjects. StaticObjects come in the form of the flag. That's done in the global.asa that we saw in Lesson 09. I'll demonstrate it again down below.

By contrast, the Contents collection is demonstrated above. It allows you to set and retrieve variables with Application scope. The format for setting an Application variable is Application.Contents("VariableName")="VariableValue". However, since Contents is the default Collection, we have a little shortcut for setting Application variables. The shortcut goes like this: Application("VariableName")="VariableValue".

Share the Variable:

One last thought on Application Variables. The application variable is shared by all visitors. Let's say that you and I are on the same ASP web site at the same time. If you set the background color to white in script11.asp, then I will see "white" as the official color if I go directly to script11a.asp. Application Variables are by no means the most efficient means of passing information from one user to another.

No Apartment Model:

You may notice that the example above seems to be inefficient. Why not just directly assign Application("OfficialColor") = Request.Form("OfficialColor")? Because we can't. By design, the newer (and updated) versions of Microsoft server software intentionally do not support Apartment Model Behavior.

Application Methods:

The two Application Methods are Lock() and Unlock(). Lock() blocks all other users from changing the Application variables. Unlock() releases control so that other users can change it. That's important on a larger site where multiple users may be trying to access the same page at the same time.

Application Events:

The two Application events are Application_OnStart() and Application_OnEnd(). These events are accessed in the global.asa. Let's repeat that script from lesson 09.







Misc. Items:

Application.Contents has two methods of its own. Application.Contents.Remove("VariableName") and Application.Contents.RemoveAll().

You'll notice there are also Session Events in the global.asa. We'll deal with those in Lesson 12. You'll also notice a call to the ADO Library. We'll talk about that when we get to databases.


------------------------------- 12 -----------------------------------

ession Object

Overview:

The Session Object is how you track a single user across many pages. It has four (4) properties, two (2) collections, one (1) method, and two (2) events.

Get Started:

In this series of examples we will create a password system. We will use the Session Object to track whether or not a user is authorized to view certain pages. Below are several scripts for lesson12. Look at them, play with, and then read the explanations that come further down the page.

<%@LANGUAGE="JavaScript"%>
<%
//No ASP Here, just a regular HTML Page
%>

To play along with our password page, put in a user name and a password.


The correct user name is guest.

And the correct password is also guest.


User:

Pass:





Click Here to run script12.asp in a new window. Below is script12a.asp.

<%@LANGUAGE="JavaScript"%>
<%
var userName=new String(Request.Form("userName"))
var userPassword=new String(Request.Form("userPassword"))
if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}
else
{
Session("Authorized")=false
%>

You did not supply the correct Name & Password.

Click here to log in.

<%
} //end else statement
%>

We'll skip over script12b.asp entirely because it's almost exactly the same as script12c.asp. Down below is script12c.asp.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
%>

The second of two pages that are password protected.

Click Here to log out.

<%
} //end of else statement
%>

Above is script12c.asp, which is the second of two password-protected pages. Below is script12.asp, which is the logout page.

<%@LANGUAGE="JavaScript"%>
<%
if (Session("Authorized")!=true)
{
%>

You are not an authorized user.

Click here to log in.

<%
}
else
{
var SessionID=Session.SessionID
Session.Abandon()
%>

You have sucessfully logged out.

This was session <%=SessionID%>.


Now try a link to one of the
pages you've already visited.


script12b.asp

script12c.asp

script12d.asp


<%
} //end of else statement
%>

A Quick Explanation:

After all that, the last thing you want to see is another grey box full of code. Sorry to do it one more time but, the keystone to this system is in script12a.asp. I've reprinted it down below.

if (userName=="guest" && userPassword=="guest")
{
Session("Authorized")=true
Response.Redirect("script12b.asp")
}

Any page can now be turned into a password protected page with the following line: if (Session("Authorized")!=true). Session Variables are part of the Session Collections. Let's talk about them.

Session Collections:

The two Session Collections are Session.Contents and Session.StaticObjects. They parallel the Application.Contents and Application.StaticObjects.

Using Session.Contents("someVariable")="someValue" we can set Session Variables. These variables allow us to carry values from one page to the next. Since Contents is the default collection we can use a little shortcut. It goes like this: Session("someVariable")="someValue".

The shortcut is what you saw in the scripts above.

Session.Contents has two methods of its own. They are Session.Contents.Remove("variableName") and Session.Contents.RemoveAll().

We did not demonstrate StaticObjects in the scripts above. It comes in the form of the flag (set for Session scope).

No Sharing:

Remember how Application variables could be shared by all viewers on your ASP web site? That's not so with Session Variables. They are private; Session Variables are to be accessed only by one user.

Session.Abandon( ):

My bet is you could figure out Session.Abandon() without any explanation. However, let me just state for the record that Session.Abandon() ends the user's session and releases the Session Variables from memory.

Session Properties:

Let's briefly discuss two properties you are not likely to use. Session.CodePage lets you call for foreign character sets, like Chinese or Russian. Session.LCID is a location identifier. It determines the time zone and language for the server. Don't mess with it.

Now let's move on to something you might actually use from time to time. Session.SessionID is a read-only property generated by the server, and assigned to one specific user during one specific session. The SessionID follows the user from the beginning of the session until the end.

Session.Timeout is the number of minutes that a user can be idle before the Server ends the user's individual session and reclaims the memory that was allocated to Session Variables. (Session.Timeout is demonstrated in the global.asa in lesson 10.)

Session Events:

The two Session events are Session_OnStart() and Session_OnEnd(). These events are accessed in the global.asa. You can see an example of global.asa in lesson 10.

What's Next:

We've seen in the last two lessons that Apartment Model Behavior is strictly forbidden in the Application Intrinsic Object. (It's not forbidden in the Session Object, but it is restricted.) So how do we store values (functions in particular) for reuse in many scripts? That is the subject of Lesson 13.


------------------------------- 13 -----------------------------------

nclude Files

Server Side Includes:

Experienced JavaScript programmers know that code reuse is good. Experienced JavaScript programmers also know that JavaScript functions are data types.

So, we should be able to store a JavaScript function inside a Session Variable or an Application Variable, right? Unfortunately, no. The way to reuse JavaScript functions across many pages is to use SSI: Server Side Includes.

<%@LANGUAGE="JavaScript"%>


ASP JavaScript Lessons(8-14)-speakitnow-ChinaUnix博客