201506120856_ "javascript--client and server-side communication"

Source: Internet
Author: User
Tags setcookie

In a Web project, the interaction between the client and the server can be implemented by means of cookies, hidden frames, HTTP requests, LiveConnect requests, and smart HTTP requests.

A Cookies

Cookies are the means by which the first JavaScript can take advantage of the client-server interaction. When the browser sends a request to the server, the cookie stored for the server is sent to the server along with other information. This allows JavaScript to set a cookie on the client, which can then be read by the server side.

1. The composition of the cookie

Name-Each cookie is represented by a unique name. This name can contain letters, numbers, and underscores. Case insensitive.

Value-The string value that is stored in the cookie. This value must be encoded with encodeuricomponent () before it is stored to avoid losing data or consuming cookies. The number of bytes added to the name and value cannot exceed 4095 bytes, which is 4KB.

Domain-For security reasons, websites cannot access cookies created by other domains. After the cookie is created, the domain information is stored as part of the cookie. However, although this is not common, you can override this setting to allow another site to access this cookie.

Path-the security feature of another cookie that restricts access to a specific directory on the Web server. For example, you can specify that cookies can only be accessed from Http://www.wrox.com/books.

Expiration Date--determines when the cookie is deleted. By default, cookies are deleted when you close the browser, but you can set the deletion time yourself. This value is a GMT-formatted date (you can use the toGMTString () method of the Date object) to establish the exact time at which the cookie should be deleted. If the date set is the time before the current date, the cookie is immediately deleted.

Security flag--used to indicate whether a cookie can only be accessed from a secure Web site (a website that uses SSL and HTTPS protocols). This value can be set to true to enhance protection and thus ensure that cookies are not accessed by other websites.

2. Other security restrictions

i) each domain can only 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 single user's machine cannot exceed 30.

3. Cookies in JavaScript

Let's look at a function that sets a cookie as follows:

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 has only the first two arguments, and the function calls the following method:

Setcookie ("name", "pistachio");

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 of obtaining a cookie based on the name of a cookie, as follows:

function GetCookie (sName) {
var sre= "(?:;.)?" + SName + "= ([^;] *);?;
var ore= new RegExp (SRE);
if (Ore.test (Document.cookie)) {
Return decodeURIComponent (regexp["$");
} else {
return null;
}
}

Call this method to get a cookie with the specified name, as in the following example:

var sName = GetCookie ("name");

Next we write a function to delete the cookie, just set the expiration time to the last time, the code is as follows:

function Deletecookie (SName, spath, Sdomain) {

Setcookie (SName, "", New Date (0), spath, Sdomain);

}

4. Server-Side Cookies

1) JSP

The JSP provides a very simple interface for handling cookies, and the request object is automatically initialized when the JSP is executed, and there is a method GetCookies () method that returns an array of Cookie objects. Each cookie object has GetName (), GetPath (), GetDomain (), Getsecure (), Getmaxage () and so on, and we'll look at a way to get a cookie:

public static Cookie GetCookie (HttpServletRequest request, String name) {

cookie[] cookies = request.getcookies ();

if (cookie = null) {

for (int i = 0; i<cookies.length; i++) {

if (Cookies[i].getname (). Equals (name)) {

return cookies[i];

}

}

}

}

Let's take a look at how to create a new cookie:

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

Namecookie.setdomain ("http://www.wrox.com");

Namecookie.setpath ("/books");

Response.addcookie (Namecookie);

To delete a cookie, you can use the following methods:

Cookie cookietodelete = GetCookie ("name");

Cookietodelete.setmaxage (0);

Response.addcookie (Cookietodelete);

2) ASP.

Slightly.

3) PHP

Slightly.

Two Hide Frame

The method is to create a 0-megapixel frame that can communicate with the server using JavaScript. This means of communication requires two parts: a JavaScript object for handling client communication and a special page that handles communication on the server. Eg.

Examples of <title> hidden frames </title>

<frameset rows= "*, 0" >

<frame src= "test1.html" nam= "MainFrame"/>

<frame src= "hidden.html" nam= "Hiddenframe"/>

</frameset>

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

function Getserverinfo () {

parent.frames["Hiddenframe"].location.href = "hiddenframecom.html";

}

The code for the function Handleresponse () that handles the response is as follows:

function Handleresponse (SRESPONSETEXTT) {

Alert ("Server returned:" + sresponsetextt);

}

The page that handles the hidden request must output a normal HTML page with a <textarea/> element that contains the returned elements. With <textarea/> you can easily handle multiple rows of data, and this page must call the Handleresponse () function in the main frame. The instance code is as follows:

Examples of <title> hidden frames </title>

<script type= "Text/javascript" >

Window.onload = function () {

Parent.frames[0].handleresponse (

document.forms["Formresponse"].result.value);

};

</script>

<body>

<form name= "Formresponse" >

<textarea name= "Result" > Data transferred back </textarea>

</form>

</body>

Three HTTP request

Many browsers now have the ability to initialize HTTP requests directly from JavaScript and get results without having to hide frames and other trickery tips.

At the heart of this exciting new feature is the XML HTTP request object that Microsoft created. This object is present with MSXML until its ability has been fully mined recently. An XML HTTP request is essentially an additional generic HTTP request that adds the functionality to send and receive XML code.

To re-create the XML HTTP request object in IE, or to use ActiveXObject, as follows:

var orequest = new ActiveXObject ("Microsoft.XMLHTTP");

Let's look at a way to create 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 ("No msxml! installed on your machine");

}

After the HTTP request is created, the open () method can be used to specify the request to be sent, and the parameters of the method are described below:

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

Second parameter: the requested URL;

The third parameter: A Boolean value that indicates whether the request was sent asynchronously.

Eg. Orequest.open ("Get", "Example.txt", false);

When open, the Send () method can be used for sending the request, which takes a parameter, which can be null,

eg. Orequest.send (NULL);

Let's look at a more complete example:

var orequest = Createxmlhttp ();

Orequest.open ("Get", "Example.txt", false);

Orequest.send (NULL);

Alert ("Status:" + Orequest.status + "(" + Orequest.statustext + ")");

Alert ("text message for response:" + Orequest.responsetext);

This example gets a plain text file on the server side, and then displays the content.

If you send an asynchronous request, you must use the onReadyStateChange event handler and check that the readystate attribute is equal to 4 (as with the XML DOM). Let's look at an example:

var orequest = Createxmlhttp ();

Orequest.open ("Get", "Example.txt", true);

Orequest.onreadystatechange = function () {

if (orequest.readystate = = 4) {

Alert ("Status:" + Orequest.status + "(" + Orequest.statustext + ")");

Alert ("text message for response:" + Orequest.responsetext);

}

}

Orequest.send (NULL);

1. Using the HTTP header

The XML HTTP request object provides a way to get the HTTP headers and set them up:

L getallresponseheaders (): Returns the string containing the HTTP header information for all responses;

L getResponseHeader (): Gets the name of the header that is specified for a header, the parameter is obtained, eg. var svalue = Orequest.getresponseheader ("Server");

L Setresponseheader (): Sets the header information for the XML HTTP request, eg. Orequest. Setresponseheader ("MyHeader", "pistachio").

2. The assigned value of the implementation

Mozilla first copied the XML HTTP implementation, creating a JavaScript named XMLHttpRequest, which behaves exactly like the Microsoft version, Opera (7.6) and Safari (1.2) also copied Mozilla's implementation, creating its own XMLHttpRequest object.

3. Make a GET request

The most common type of request on the web is a GET request, so let's look at a GET request example, as shown in the following code:

First, to add the convenience of a parameter, let's add a method that adds a parameter, and then build a URL for the request, as shown in the following code:

function Addurlparam (URL, sparamname, sParamValue) {

URL + = (Url.indexof ("?") = =-1? "?": "&");

URL + = encodeURIComponent (sparamname) + "=" + encodeURIComponent (sParamValue);

return URL;

}

var url = "Http://www.blogjava.net/amigoxie";

url = addurlparam (URL, "Gender", "female");

url = addurlparam (URL, "Age", "25");

Orequest.open ("Get", url, false);

4. Making a POST request

Post requests are used for the submission process after data is entered in the form, because post can send more data (up to 2GB) 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);

Four LiveConnect Request

LiveConnect is introduced by Netscape Navigator, which generally allows JavaScript to interact with Java classes. The user must install the JRE and also enable Java in the browser.

1. Make a GET request

When you use live Connect, you must provide the full name of the class to initialize a Java object. Once the URL is created, you can open an input stream and use the reader to read the data. The best approach is to create a inputstreamreader and then create a bufferreader based on it, with the following instance code:

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 the XML HTTP request object, LiveConnect requires the full URL of the request to be entered, starting with http://, because the Java object does not have any context that interprets the relative URL.

2. Making a POST request

Because the POST request can be considered bidirectional, the connection must be set to accept input and output using the Setdoinput () and Setdooutput () methods. In addition, the connection should not use any cached data, so call Setusecaches (false). As with the XML HTTP request object, you must also set Content-type to the appropriate value using the Setrequestproperty () method. 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;

}

Five Smart HTTP Requests

For two completely different HTTP request methods, there are a number of common functions that can be useful for development.

1. Get () method
This method is used to make a GET request to the specified URL. The method has two parameters: the URL to send the request and a callback function. Callback functions are used in many programming languages to notify developers at the end of a request. The consolidated common 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 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!");

}

}

201506120856_ "javascript--client and server-side communication"

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.