Javascript advanced Article 3 Introduction to Ajax, JSON, and Prototype

Source: Internet
Author: User

Ajax
I have heard a lot about this word, but I have never really touched it, so I 'd like to know it here.
The innovation of Ajax technology is that it improves the traditional "request-wait-response-refresh-return data" mode. Before returning information, users can continue their operations, the current page will not be refreshed due to requests. This greatly improves interactivity.
Ajax is actually not a technology, but composed of many technologies. One of the biggest features is that it can be asynchronously transmitted to implement multi-threaded services.
Ajax asynchronous transmission relies on the XMLHttpRequst object in js, so we start with it.
XMLHttpRequest is an abstract object created by XMLHttp for data interaction. In IE, XMLHttpRequest is used as an ActiveX control and as a built-in js object in FF Opera.
Code for creating an XMLHttpRequest object: Copy codeThe Code is as follows: <script type = "text/javascript">
Var xmlHttp = false;
Var headType = "";
Function createXmlRequest (){
If (window. ActiveObject) {// IE
Try {
XmlHttp = new ActiveXObject ("Msxml2.XMLHTTP ");
} Catch (e ){
Try {
XmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ");
} Catch (e ){
Window. alert ("create XML Request failed" + e );
}
}
} Else if (window. XMLHttpRequest) {// FF
XmlHttp = new XMLHttpRequest ();
}
If (! XmlHttp ){
Window. alert ("create XML Request failed ");
}
}
</Script>

ReadyState attributes:
0 = initialization not 1 = initialization 2 = Sending data 3 = data transfer in 4 = complete
ResponseText attributes:
1, 2 = responseText is an empty string 3 = Receiving 4 = receiving complete
ResponseXML attributes:
After sending () is executed, if the returned data is in the correct xml format, you can use XMLHttpRequest to receive the returned data. ResponseXML can format the returned information as an XML Document object. If the type is text or xml, null is returned.
Status attribute:
After the send () attribute is sent, you can use this attribute only when ReadyState is 3 or 4. Otherwise, an error occurs when reading status. The following are common examples:
100 = the customer must continue to send the request 200 = Transaction success 400 = Error request 403 = request not allowed 404 = no file found, query or URL 500 = internal server error 502 = currently unavailable server 505 = the server does not support or reject the HTTP Version specified in the request header.
StatusText attributes:
After sending (), read the transaction status through statusText. statusText returns the status row of the current HTTP request. This attribute can be used only when readyState is 3 or 4. Otherwise, an error occurs.
Onreadystatechange event:
The operation to be performed when the event property value changes.
Abort () method:
Stop an XMLHttpRequest object's HTTP request and restore the object to its initial state.
Open () method:
Create a new HTTP request and specify the method, URL, and authentication information. The syntax is xmlHttp. open (method, url, mode, user, psd );
Method indicates the request method, including post, get, and put. case insensitive. The url is the destination address, and the mode parameter is the second type. It specifies whether the request is asynchronous. The default value is true.
After the open () method is called, The readyState attribute is set to 1.
Send () method:
XmlHttp. send (content); content is the content to be sent, which cannot be ignored.
SetRequestHeader () method:
SetRequestHeader (header, value) sets the information of a single HTTP header. When readyState is 1, you can call this method after open (); otherwise, an exception is returned, if it already exists, the original one will overwrite it. Value is a string type data that represents the value of the header name.
GetResponseHeader () method:
By reading the header information, you can read content-type (content type), content-length (content length), last-modify (last modification) date, and so on, depending on the specific website.
GetAllResponseHeaders () method:
Obtain all the header information.
The following example shows how to obtain the header information:Copy codeThe Code is as follows: <Head>
<Title> Ajax test </title>
<Script type = "text/javascript">
Var xmlHttp = false;
Var headType = "";
Function createXmlRequest (){
If (window. ActiveObject) {// IE
Try {
XmlHttp = new ActiveXObject ("Msxml2.XMLHTTP ");
} Catch (e ){
Try {
XmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ");
} Catch (e ){
Window. alert ("create XML Request failed" + e );
}
}
} Else if (window. XMLHttpRequest) {// FF
XmlHttp = new XMLHttpRequest ();
}
If (! XmlHttp ){
Window. alert ("create XML Request failed ");
}
}
Function HeadRequst (request ){
CreateXmlRequest ();
HeadType = request;
XmlHttp. onreadystatechange = getHeadInfo; // register the callback function without parentheses.
XmlHttp. open ("HEAD", "http://www.baidu.com/", false );
XmlHttp. send (null );
}
Function getHeadInfo (){
Var span = document. getElementById ("state ");
If (xmlHttp. readyState = 4 ){
If (headType = "All ")
Span. innerHTML = xmlHttp. getAllResponseHeaders ();
Else {
Span. innerHTML = headType + ":" + xmlHttp. getResponseHeader (headType );
}
}
}
</Script>
</Head>
<Body>
<Center>
<Input type = "button" onclick = "HeadRequst ('content-type')" value = "Content-Type"> <br>
<Input type = "button" onclick = "HeadRequst ('date')" value = "Date"> <br>
<Input type = "button" onclick = "HeadRequst ('connection')" value = "Connection"> <br>
<Input type = "button" onclick = "HeadRequst ('all')" value = "All headers"> <br>
<Br>
<Span id = "state"> </span> <br>
</Center>
<Body>
</Html>

This example worked very well in IE. The reason for MS is that FF does not support ActiveX... Ask the experts to solve the problem... Rz
JSON
The full name of JSON is: javascript object notation object flag. It is a lightweight text-based and language-independent data exchange format. Similar to XML, it is a text organization format, such:
<User>
<Name> Dumpling </name> <gender> Famle </gender> <age> 22 <age>
<User>
In JSON format:
"User": [{"name": "Dumpling", "gender": "Famle", "age": 22}]
The advantage is that it can simplify the parsing and storage of acquired data.
If the preceding example is more complex, we can see the specific JSON format. When we declare it in JS, we can write it like this:Copy codeThe Code is as follows: var users = {
"Users ":[
{"Name": "Dumpling", "gender": "Famle", "age": 22 },
{"Name": "Sanday", "gender": "Famle", "age": 20 },
{"Name": "Shine", "gender": "Famle", "age": 18}
]};

Data is encapsulated using JSON. stringify (obj. Obj can encapsulate a class by itself.
We don't need to write strings by ourselves. We only need to give values and then encapsulate them with functions. Here is a simple example:Copy codeThe Code is as follows: <Head>
<Title> testing </title>
<Script language = "javascript">
Function user (name, age, gender ){
This. userName = name;
This. userAge = age;
This. userGender = gender;
}
Function submidForm (){
Var subForm = document. jsonForm;
Var userTable = document. getElementById ("users ");
Var newRow = userTable. insertRow (-1); // insert one row at the end of table
NewRow. insertCell (0). innerHTML = subForm. name. value;
NewRow. insertCell (1). innerHTML = subForm. gender. value;
NewRow. insertCell (2). innerHTML = subForm. age. value;
Var newuser = new user (subForm. name. value, subForm. age. value, subForm. gender. value );
Var jsonStr = JSON. stringify (newuser );
Alert (jsonStr );
SubForm. name. value = "";
SubForm. age. value = "";
}
</Script>
</Head>
<Body>
<Center>
<Form method = "POST" action = "#" name = jsonForm>
<Table border = "1" id = "newuser">
<Tr>
<Td> Name: </td> <input type = "text" name = "name"> </td>
<Td> Gender: </td>
<Td> <select name = "gender">
<Option value = "Famle"> Famle </option>
<Option value = "Male"> Male </option>
</Select>
</Td>
<Td> Age: </td> <input type = "text" name = "age"> </td>
</Tr>
<Tr>
<Td colspan = "6" align = "center">
<Input type = "button" id = "submit" value = "Submit" onclick = "submidForm ()"> </input> </td>
</Tr>
</Table>
</Form>
<Table id = "users" border = "1" width = "450">
<Tr> <td> Name </td> <td> Gender </td> <td> Age </td>
</Table>
</Center>
</Body>
</Html>

The fear is too long for me to hide it. The result is like this:

Of course, if you want to encapsulate a large number of users at a time, such as submitting five or six users and then encapsulating them in JSON format at a time, you can put these users in an Arry, then, use arry as the stringify parameter. Just give it a try ~ I will not be able to access the code ~

Parse and assign values to JSON in JS

This piece is even the center of the json, and its Parsing is actually very simple, such as the previous example,

Copy codeThe Code is as follows: var usersJson = {
"Users ":[
{"Name": "Dumpling", "gender": "Famle", "age": 22 },
{"Name": "Sanday", "gender": "Famle", "age": 20 },
{"Name": "Shine", "gender": "Famle", "age": 18}
],
"Objects ":[
{"Name": "food", "price": 55}
]
};

So if I want to get the sanday value, I can write it like this: var username = uersJson. users [1]. name; this will happen, and there will be no other problems ~
If you want to modify the data, assign a value directly. For example, I want to modify the food price userJson. objects [0]. price = 43;
As for determining whether the input is legal or not, I am too lazy to write it. It takes time.
JSON is here, and the last part is coming.
Prototype framework
First go to prototype website: http://www.prototypejs.org/
In fact, it is a lot of expansion of JS, which is generally composed of two parts: general method and template. For general methods, such as $ () $ A (), templates are used to expand the internal classes of JS and provide support templates for various Ajax applications. For details, refer to the website provided here. For two examples, please go to the API page to view more: http://api.prototypejs.org/(yes, I am very lazy wait) Wait)
$ () Method: gets an element object. It is similar to the getElementById method and can accept multiple parameters and return an array.
$ () Method: Get the specified element array. Similar to the getElementByTagName () method, the object is obtained based on the tag name.
Ajax object: as we have said just now, we need to write a lot of judgment code because of different browsers, so prototype is designed for us, Ajax. the Request object encapsulates the code for creating the XMLHttpRequest object and a variety of common methods for processing the information returned by the server, so it is still very useful. For more information, see the above API Link (= !)
Form object: because it is very common, form is also the focus of prototype, this part is very important, so you can refer to the relevant parts of the API ......

Related Article

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.