JavaScript Study Notes-client-to-Server Communication

Source: Internet
Author: User
Tags setcookie

In a Web project, you can use cookies, hidden frameworks, HTTP requests, LiveConnect requests, and smart HTTP requests to achieve client-to-server interaction,

1. cookie

Cookie is the first client-server interaction method that JavaScript can use. When a browser sends a request to the server, the cookie stored for the server will be sent together with other information to the server. This allows JavaScript to set a cookie on the client, and then the server can read it.

1. cookie Components

Name-each cookie is represented by a unique name. The name can contain letters, numbers, and underscores. Case Insensitive.

Value -- the string value stored in the cookie. This value must be encoded with encodeURIComponent () before being stored to avoid data loss or cookie occupation. The sum of names and values cannot exceed 4095 bytes, that is, 4 kb.

Domain-in security considerations, the website cannot access cookies created by other domains. After a cookie is created, the domain information is stored as part of the cookie. However, this setting can be overwritten to allow another website to access the cookie.

Path-the security feature of another cookie. The path limits access to a specific directory on the Web server. For example, you can specify that the cookie can only be renewed from http://www.wrox.com/books.

Expiry date: determines when the cookie is deleted. By default, when the browser is closed, the cookie will be deleted, but you can set the deletion time on your own. This value is a Date in GMT format (you can use the toGMTString () method of the Date object), used to determine the exact time when the cookie should be deleted. If the set date is the time before the current date, the cookie is immediately deleted.

Security Flag-Indicates whether a cookie can only be accessed from a secure website (a website using SSL and https protocols. You can set this value to true to enhance protection and prevent cookies from being accessed by other websites.

2. Other security restrictions

I) each domain can store up to 20 cookies on a single user's machine;

Ii) the total size of each cookie cannot exceed 4096 bytes;

Iii) the total number of cookies on a user's machine cannot exceed 30.

3. cookie in JavaScript

The following is a function for setting cookies:

Function setCookie (sName, sValue, oExpires, sPath, sDomain, bSecure ){
Var sCookie = sName + "=" + encodeURIComponent (sValue );
If (oExpires ){
SCookie + = "; expires =" + oExpires. toGMTString ();
}
If (sPath ){
SCookie + = "; path" + sPath;
}
If (sDomian ){
SCookie + = "; domain" + sDomain;
}
If (bSecure ){
SCookie + = "; secure ";
}
Document. cookie = sCookie;
}

The setCookie () function is only required by the first two parameters. The function call method is as follows:

SetCookie ("name", "Honey fruit ");

SetCookie ("book", "JavaScript advanced programming", new Date (Date. parse ("Jan 1, 2006 ")));

SetCookie ("message", "hello", new Date (Date. parse ("Jan 1, 2006"), "/books", http://www.wrox.com, true );

The following function is a method for obtaining a cookie Based on the cookie name. The Code is as follows:

Function getCookie (sName ){
Var sRE = "(? :;.)? "+ SName +" = ([^;] *);?;
Var oRE = new RegExp (sRE );
If (oRE. test (document. cookie )){
Return decodeURIComponent (RegExp ["$1 ");
} Else {
Return null;
}
}

 

You can call this method to obtain the cookie with the specified name. The call example is as follows:

Var sName = getCookie ("name ");

Next, we will write a function to delete the cookie. You only need to set the expiration time to the previous time. The Code is as follows:

Function deleteCookie (sName, sPath, sDomain ){

SetCookie (sName, "", new Date (0), sPath, sDomain );

}

 

4. server-side cookies

1) JSP

Jsp provides a very simple interface for processing cookies. The request object is automatically initialized when the JSP is executed. There is a method to return a cookie object array, getCookies. Each Cookie object has methods such as getName (), getPath (), getDomain (), getSecure (), and getMaxAge (). The following describes how to obtain the Cookie:

Public static Cookie getCookie (HttpServletRequest request, String name ){

Cookie [] cookies = request. getCookies ();

If (cookies! = Null ){

For (int I = 0; I <cookies. length; I ++ ){

If (cookies [I]. getName (). equals (name )){

Return cookies [I];

}

}

}

}

Next let's take a look at how to create a cookie:

Cookie nameCookie = new Cookie ("name", "Amigo ");

NameCookie. setDomain (http://www.wrox.com ");

NameCookie. setPath ("/books ");

Response. addCookie (nameCookie );

To delete a cookie, use the following method:

Cookie cookieToDelete = getCookie ("name ");

CookieToDelete. setMaxAge (0 );

Response. addCookie (cookieToDelete );

2) ASP. NET

.

3) PHP

.

 

Ii. Hide the framework

The method is to create a 0 pixel high framework that can communicate with the server using JavaScript. This communication method requires two parts: the JavaScript Object used for processing client communication and the special page for processing communication on the server. Eg.

<Html>

<Head>

<Title> example of hiding a framework </title>

</Head>

<Frameset rows = "*, 0">

<Frame src00000000test1.html "nam =" mainFrame "/>

<Frame src00000000denden.html "nam =" hiddenFrame "/>

</Frameset>

</Html>

In the first framework, two functions are defined, one for sending requests to the server and the other for processing responses. The request sending function is as follows:

Function getServerInfo (){

Parent. frames ["hiddenFrame"]. location. href = protected hiddenframecom.html ";

}

The code for processing the response function handleResponse () is as follows:

Function handleResponse (sResponseTextt ){

Alert ("server return:" + sResponseTextt );

}

The page for processing hidden requests must output a common HTML page with an <textarea/> element that contains the returned element. You can use <textarea/> to conveniently process multiple rows of data. This page must call the handleResponse () function in the main framework. The instance code is as follows:

<Html>

<Head>

<Title> example of hiding a framework </title>

<Script type = "text/javascript">

Window. onload = function (){

Parent. frames [0]. handleResponse (

Document. forms ["formResponse"]. result. value );

};

</Script>

</Head>

<Body>

<Form name = "formResponse">

<Textarea name = "result"> returned data </textarea>

</Form>

</Body>

</Html>

 

Iii. HTTP request

Currently, many browsers can initialize HTTP requests directly from JavaScript and obtain results without hiding the framework or other tips.

The core of this exciting new feature is the xml http request object created by Microsoft. This object appears together with MSXML and is fully mined until recently. Xml http requests are essentially additional common HTTP requests that are used to send and receive XML code.

To re-create an xml http request object in IE, use ActiveXObject, as shown below:

Var oRequest = new ActiveXObject ("Microsoft. XMLHTTP ");

Let's look at a method for creating xml http:

Function createXMLHTTP (){

Var arrSignatures = ["MSXML2.XMLHTTP. 5.0", "MSXML2.XMLHTTP. 4.0 ",

"MSXML2.XMLHTTP. 3.0", "MSXML2.XMLHTTP ",

"Microsoft. XMLHTTP"];

For (var I = 0; I <arrSignatures. length; I ++ ){

Try {

Var oRequest = new ActiveXObject (arrSignatures [I]);

Return oRequest;

} Catch (oError ){

// Ignore

}

}

 

Throw new Error ("MSXML is not installed on your machine !");

}

After creating an HTTP request, you can use the open () method to specify the request to be sent. The parameters of this method are described as follows:

The first parameter: The value can be "get", "post", or other HTTP methods supported by the server;

The second parameter is the request URL;

Third parameter: Boolean value indicating whether the request is sent asynchronously.

Eg. oRequest. open ("get", example example.txt ", false );

After the function is enabled, the send () method can be used to send requests. This method requires a parameter, which can be null,

Eg. oRequest. send (null );

Here is a complete example:

Var oRequest = createXMLHTTP ();

ORequest. open ("get", using example.txt ", false );

ORequest. send (null );

Alert ("status:" + oRequest. status + "(" + oRequest. statusText + ")");

Alert ("response text:" + oRequest. responseText );

In this example, a plain text file on the server is obtained and the content is displayed.

If an asynchronous request is sent, you must use the onreadystatechange event processing function and check whether the readyState feature is 4 (same as the xml dom ). Let's take an example:

Var oRequest = createXMLHTTP ();

ORequest. open ("get", example example.txt ", true );

ORequest. onreadystatechange = function (){

If (oRequest. readyState = 4 ){

Alert ("status:" + oRequest. status + "(" + oRequest. statusText + ")");

Alert ("response text:" + oRequest. responseText );

 

}

}

ORequest. send (null );

1. Use the HTTP Header

Xml http request objects provide methods to get http headers and set them:

L getAllResponseHeaders (): returns a string containing the HTTP header information of all responses;

L getResponseHeader (): gets a specified header. The parameter is the name of the obtained header. For example, var sValue = oRequest. getResponseHeader ("Server ");

L setResponseHeader (): Set the header information of the xml http request, such as eg. oRequest. setResponseHeader ("myheader", "a honey fruit ").

2. Implemented value assignment Products

Mozilla first copied the xml http implementation and created JavaScript named XMLHTTPRequest. The behavior is exactly the same as that of Microsoft. Opera (7.6) and Safari (1.2) also copied the implementation of Mozilla, you have created your own XMLHTTPRequest object.

3. GET request

The most common request type on the Web is GET request. Let's look at an example of a GET request. The Code is as follows:

First, for the convenience of adding parameters, let's add a method for adding parameters, and then construct a URL for the request. The Code is as follows:

Function addURLParam (url, sParamName, sParamValue ){

Url + = (url. indexOf ("?") =-1? "?" : "&");

Url + = encodeURIComponent (sParamName) + "=" + encodeURIComponent (sParamValue );

Return url;

}

Var url = "http://www.blogjava.net/amigoxie.pdf ";

Url = addURLParam (url, "gender", "female ");

Url = addURLParam (url, "age", "25 ");

ORequest. open ("get", url, false );

4. POST requests

POST requests are used for the submission process after data is input in the form, because the POST request can send more data (up to 2 GB) than the GET method ). Let's take a look at an example:

Function addPostParam (sParams, sParamName, sParamValue ){

If (sParams. length> 0 ){

SParams + = "&";

}

Return sParams + encodeURIComponent (sParamName) + "=" + encodeURIComponent (sParamValue );

}

 

Var sParams = "";

SParams = addPostParam (sParams, "gender", "female ");

SParams = addPostParam (sParams, "age", "25 ");

ORequest. open ("open", "test. jsp", false );

ORequest. send (sParams );

 

Iv. LiveConnect requests

LiveConnect is introduced by Netscape Navigator, which generally enables JavaScript to interact with Java classes. You must install JRE and enable Java in your browser.

1. GET request

To use Live Connect, you must provide the full name of the class to initialize a Java object. After creating a URL, you can open an input stream and use a reader to read data. The best way is to create an InputStreamReader and then create a BufferReader Based on it. The instance code is as follows:

Function httpGet (url ){

Var ourl = new java.net. URL (url );

Var oStream = ourl. openStream ();

Var oReader = new java. io. BufferedReader (new java. io. InputStreamReader (oStream ));

Var oResponseText = "";

Var sLine = oReader. readLine ();

While (sLine! = Null ){

OResponseText + = sLine + "\ n ";

SLine = oReader. readLine ();

}

OReader. close ();

Return oResponseText;

}

Note: Unlike xml http request objects, LiveConnect requires that you enter the complete request URL, starting with http: //, because the Java object does not have any context to interpret the relative URL.

2. POST requests

Because POST requests can be viewed as bidirectional, you must use the setDoInput () and setDoOutput () Methods to set the connection to accept input and output. In addition, the connection should not use any cached data, so setUseCaches (false) must be called ). Like an xml http request object, you must use the setRequestProperty () method to set "Content-Type" to the corresponding value. The Code is as follows:

Function httpPost (url, sParams ){

Var ourl = new java.net. URL (url );

Var oConnection = ourl. openConnection ();

 

OConnection. setDoInput (true );

OConnection. setDoOutput (true );

OConnection. setUseCaches (false );

OConnection. setRequestProperty ("Content-Type ",

"Application/x-www-form-urlencoded ");

 

Var output = new java. io. DataOutputStream (oConnection. getOutputStream ());

Output. writeBytes (sParams );

Output. flush ();

Output. close ();

 

Var sLine = "", sResponseText = "";

Var input = new java. io. DataInputStream (oConnection. getInputStream ());

SLine = input. readLine ();

While (sLine! = Null ){

SResponseText + = sLine + "\ n ";

SLine = input. readLine ();

}

 

Input. close ();

Return oResponseText;

}

 

5. Smart HTTP requests

For two completely different HTTP request methods, a series of common functions will be very helpful for development.

1. get () method
This method is used to make a GET request to a specified URL. This method has two parameters: the request URL and a callback function. Callback functions are used in many programming languages to notify developers when a request ends. The integrated general get () method code is as follows:

Var bXmlHttpSupport = (typeof XMLHttpRequest = "object" | window. ActiveXObject );

Http. get = function (url, fnCallback ){

If (bXmlHttpSupport ){

Var oRequest = new XMLHttpRequest ();

ORequest. open ("get", url, true );

ORequest. onreadystatechange = function (){

If (oRequest. readyState = 4 ){

FnCallback (oRequest. responseText );

}

}

ORequest. send (null );

} Else if (navigator. javaEnabled () & typeof java! = "Undefined"

& Type java.net! = "Undefined "){

SetTimeout (function (){

FnCallback (httpGet (url ));

}, 10 );

} Else {

Alert ("your browser does not support HTTP requests !");

}

}

2. post () method

In addition to the three parameters (URL, parameter string, and callback function), the post () method is similar to the get () method. The Code is as follows:

Var bXmlHttpSupport = (typeof XMLHttpRequest = "object" | window. ActiveXObject );

Http. post = function (url, sParams, fnCallback ){

If (bXmlHttpSupport ){

Var oRequest = new XMLHttpRequest ();

ORequest. open ("post", url, true );

ORequest. setRequestHeader ("Content-Type ",

"Application/x-www-form-urlencoded ");

ORequest. onreadysatechange = function (){

If (oRequest. readyState = 4 ){

FnCallback (oRequest. responseText );

}

}

} Else if (navigator. javaEnabled () & typeof java! = "Undefined"

& Type java.net! = "Undefined "){

SetTimeout (function (){

FnCallback (httpPost (url, sParams ));

}, 10 );

} Else {

Alert ("your browser does not support HTTP requests !");

}

}


Author: Ha full text

Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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