JavaScript advanced Programming-Reading notes (6)

Source: Internet
Author: User

20th Chapter JSON

JSON is a lightweight data format that simplifies the effort to represent complex data structures

The JSON syntax can represent three types of values

L Simple values: using the same syntax as JavaScript, you can represent strings, numeric values, Booleans, and Null in JSON. However, JSON does not support special numeric undefined in JavaScript.

"Hello world!"

L object (the value of a property can be a simple value or a complex type value, as in an object embedding object)

{

"Name": "Nicholas",

"Age": 29

"School": {

"Name": "Merrimackcollege",

"Location": "North Andover, MA"

}

}

L Arrays

[+, "HI", true]

Combining arrays and objects can form a more complex set of data, such as:

[

{

"title": "Professinal JavaScript",

"Authors": [

"Nicholas C. Zakas"

],

Edition:3,

year:2011

},

{

"title": "Professinal JavaScript",

"Authors": [

"Nicholas C. Zakas"

],

Edition:2,

year:2009

}

]

ECMAScript 5 defines a native JSON object that can be used to serialize the object to a JSON string or to parse the JSON data into a JavaScript object. The Json.stringify () and Json.parse () methods are respectively used to achieve the above two functions.

The 21st chapter Ajax and Comet

The core of Ajax technology is the XMLHttpRequest object (referred to as XHR). The ability to asynchronously get more information from the server, so that when the user clicks, you can also get new data without refreshing the page.

1. XMLHttpRequest Object

(1) Usage of XHR

Use the following code to create the XHR object in all browsers:

var xhr = createrxhr ();

When using a Xhr object, the first method to invoke is open (), which accepts 3 parameters: the type of request to be sent ("get", "post", and so on), the requested URL, and a Boolean value that represents whether the request was sent asynchronously.

Calling the open () method does not actually send the request, but only initiates a request for sending.

To send a specific request, strip with the Send () method, such as:

Xhr.open ("Get", "example.php", false);

Xhr.send (NULL);

If you do not need to send data through the request principal, you must pass in NULL.

After the response is received, the data for the response is automatically populated with the properties of the Xhr object, with the following properties:

    • ResponseText: The text to be returned as the body of the response;
    • Responsexml: If the content type of the response is "text/xml" or "application/xml", this property holds the response data XML DOM document
    • Status: The HTTP status of the response;
    • Description of the Statustext:http status.

After the response is received, the first step is to check the Status property to determine that the response has returned successfully.

In most cases, to send an asynchronous request, you can detect the ReadyState property of the Xhr object, which represents the current active phase of the request/response process. The possible values are as follows:

0: Uninitialized, open () not called;
1: Start, has been called open ();
2: Send, has called send (), did not accept the response;
3: Accepted, received a partial response;
4: Complete, all responses have been received, and can already be used on the client.

The ReadyStateChange event is triggered whenever the value of the ReadyState property is changed from one value to another.

In addition, the abort () method can be called before the response is received to cancel an asynchronous request.

(2) HTTP header information

Each HTTP request and response will have the appropriate header information.

By default, the following header information is also sent at the same time that the XHR request is sent:

Accept: The type of content the browser can handle;

Accept-charset: The character set that the browser can display;

Accept-encoding: The compression encoding that the browser can handle;

Axxept-language: The language currently set by the browser;

Connection: The type of connection between the browser and the server;

Cookies: How cookies are set on the current page;

Host: The domain where the request for the ear hole page is sent;

Referer: The URI of the page that issued the request;

User-agent: The user agent string for the browser.

Use the setRequestHeader () method to set the custom request header information.

Call the getResponseHeader () method of the Xhr object and pass in the header field name to get the corresponding response header information.

The call to the Getallresponseheader () method allows you to obtain a long string containing all the header information.

(3) Get request

Get is the most common type of request and is most commonly used to query the server for certain information.

If necessary, the query string parameter can be appended to the end of the URL to send the information to the server.

The name and value of each parameter in the query string must be encoded with encodeuricomponent () before it can be placed at the end of the URL.

The following function can help to add a query string parameter to a bit of an existing URL:

function Addurlparam (url,name,value) {

URL + = (url.indexof ('? ') = =-1? '? ': ' & ');

URL +=encodeuricomponent (name) + ' = ' + encodeuricomponent (value);

return URL;

}

(4) Post request

Post requests, which are typically used to send data to the server that should be saved.

2, XMLHttpRequest Level 2

(1) Formdata facilitates the serialization of forms and the creation of the same data in form format (for transmission via XHR).

The following example creates a Formdata object and adds some data to it:

var data = new FormData ();

Data.append ("name", "Nicholas");

This append () method receives two parameters: the key and the value.

By passing the form element to the Formdata constructor, you can also fill in the key-value pairs with the form's data beforehand:

var data = new FormData (document.forms[0]);

Once you have created an instance of Formdata, you can pass it directly to the XHR send () method.

The convenience of using formdata is reflected in the need not to explicitly set the request header on the XHR object.

(2) Timeout setting

IE8 adds a timeout property to the Xhr object, indicating how many milliseconds the request waits for a response to terminate.

(3) Overridemimetype ()

Firefox first introduced the Overridemimetype () method, which overrides the MIME type of the XHR response.

3. Progress Events

The Progress Events specification defines an event related to client service communication. The following 6 progress events are available: Loadstarts, progress, error, Abort, load, loadend.

Each request starts with triggering the Loadstart event, followed by one or more progress events, then triggering one of the error, abort, or load events, ending with the triggering Loadend event.

4. Cross-source resource sharing

CORS (Cross-originresource sharing, cross-origin resource sharing) defines how the browser and the server should communicate when a cross-origin resource must be accessed.

The basic idea is to use a custom HTTP header to let the browser communicate with the server to determine whether the request or response should be successful or should fail.

(1) IE's implementation of cors

Microsoft introduced the XDR (xdomainrequest) type in IE8. This object is similar to XHR, but it enables secure and reliable cross-domain communication.

XDR objects are used in very similar ways to XHR objects. Also create an instance of Xdomainrequest, calling the open () method in the call to the Send () method.

All XDR requests are executed asynchronously and cannot be used to create a year-over request.

The XDR object also supports the Timeout property and the OnTimeOut event handler.

To support post requests, the XDR object provides the ContentType property, which is used to represent the format in which the data is sent.

(2) Other browsers ' implementation of Cors

WebKit in firefox3.5+, safair4+, Chrome, ISO, and Android platforms have native support for cors through XMLHttpRequest objects.

To request a resource that resides in another domain, use the standard XHR object and pass in the decision URL in the open () method.

(3) Preflightedreqeusts

Cors enables developers to use custom head get or Post methods, as well as different types of principal content, through a transparent server validation mechanism called Preflightedreqeusts.

(4) Request with credentials

By default, cross-origin requests do not provide credentials (cookies, HTTP authentication, and client-issued SSL certificates, etc.). You can specify that a request should send credentials by setting the Withcredentials property to True.

(5) Cross-browser cors

The simplest way to detect whether XHR supports cors is to check for the presence of withcredentials properties. By combining the detection of Xdomainrequest objects, it is possible to reconcile all browsers.

5. Other cross-domain technologies

With the ability to perform cross-domain requests in the DOM, you can send some kind of request without relying on the XHR object.

(1) Image ping

The first cross-domain request technique is the use of tags.

With an image ping, the browser does not get any specific data, but by listening to the load and error events, it can know when the response was received.

Disadvantage: Only get requests can be sent, and the response text of the server cannot be accessed.

(2) JSONP

Packed JSON or parametric JSON is a new way to apply JSON methods.

Advantage: The ability to access text directly, to support two-way communication between the browser and the server.

Disadvantage: JSONP is executed from other domains, may not be secure, and it is not easy to determine whether the JSONP request failed.

(3) Comet

Ajax is a technique for requesting data from a page to a server, while Comet is a technique by which servers push data to a page.

There are two ways to implement comet: long polling and streaming.

The advantage of polling is that all browsers support it.

(4) Server send event (SSE)

The SSE API is used to create a one-way connection to the server through which the server can send any amount of data.

To book a new stream of events, first create a new EventSource object and pass in an entry point:

var Source = new EventSource ("myevents.php");

By default, the EventSource object maintains an active connection to the server. If you want to force the immediate end to connect and no longer connect, you can call the close () method.

(5) WebSockets

The goal of WEB sockets is to provide full-duplex, bidirectional communication on a single persistent connection.

Web Sockets cannot be implemented using a standard HTTP server, only a dedicated server that supports this protocol will work properly.

To create a websocket, first instantiate an WebSocket object and pass in the URL you want to connect to:

var socket =new WebSocket ("ws://www.example.com/server.php");

To close the WebSocket connection, you can call the close () method at any time.

Socket.close ();

Once the WEB socket is open, you can send and receive data over the connection. To send data to the server, use the Send () method.

WEB sockets can only send plain text data over a connection, so for complex data structures, it must be serialized before being sent over a connection.

When the server sends a message to the customer service, the WebSocket object triggers the message event.

6. Security

To ensure that URLs accessed through XHR are secure, it is common practice to verify that the sending requestor has access to the appropriate resources.

The 23rd Chapter offline application and Client storage

Support for offline Web application development is another focus of HTML5.

Developing an offline Web application requires several steps:

The first is to ensure that the application knows whether the device can surf the Internet;

Then, the application must also have access to certain resources (images, JavaScript, CSS, etc.);

Finally, a piece of local space must be used to hold the data.

1, off-line detection

HTML5 defines a Navigator.online property for this property, which is true to indicate that the device can surf the internet and a value of false indicates that the device is offline.

To better determine whether a network is available, HTML also defines two events: online and offline. These two events are triggered separately when the network changes from offline to online or from online to offline.

In order to detect whether the application is offline, after the page is loaded, it is best to get the initial state through Navigator.online. Then, it is through the two events above to determine whether the network connection status changes.

2. Application Cache

HTML5 's application cache, referred to as AppCache. is a buffer that is separated from the browser's cache. To save data in this cache, you can use a profile (manifest file) to list the resources to download and cache.

To associate a description file with a page, you can specify the path to the file in the manifest property in

The app cache also has the appropriate JavaScript API to let you know what it's doing. The core of this API is the Applicationcache object, which has a status property with a constant value that represents the current state of the application cache as follows:

0: No cache.

1: Idle.

2: Check in.

3: Download.

4: Update complete.

5: Obsolete.

There are also many related events that indicate the change in the state of the application cache. There are: checking, error, noupdate, downloading, progress, updateready, cached.

In general, these events are triggered sequentially as the page loads in the order described above. However, you can also manually intervene by invoking the update () method to have the application cache trigger the above event to check for updates.

3. Data storage

(1) Cookies

An HTTP cookie, usually called a cookie, is initially used by the client to store session information.

    • Limit

A cookie is bound to a specific domain name in nature.

Because cookies are stored on client computers, there are some restrictions that ensure that cookies are not used maliciously and do not occupy too much disk space. The total number of cookies per domain is limited, but there is a difference between browsers.

When a cookie is set beyond the limit of a single domain name, the browser will be aware of the cookie that was previously set.

There is also a limit to the size of cookies in the browser. Most browsers have a length limit of approximately 4096B (plus minus 1).

If you try to create a cookie that exceeds the maximum size limit, the cookie will be silently discarded.

    • Composition of cookies

Cookies are composed of the following pieces of information saved by the browser: name, value, domain, path, expiration time, security flag.

    • Cookies in JavaScript

There are three types of basic cookie operations: Read, write, and delete.

(2) IE user data

In IE5.0, Microsoft introduced the concept of persistent user data through a custom behavior.

(3) Web Storage mechanism

The purpose of WEB storage is to overcome some of the limitations imposed by cookies, and it is not necessary to continuously send data back to the server when the data needs to be tightly controlled on the client.

The original Web Storage specification contained two types of object definitions: Sessionstorage and globalstorage.

(4) Indexedb

Indexedb is a structured data storage mechanism similar to SOL database.

JavaScript advanced Programming-Reading notes (6)

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.