JavaScript advanced 3 Ajax, JSON, prototype Introduction _ Basics

Source: Internet
Author: User
Ajax
This word has heard a lot, but actually did not really contact, so here a little understanding.
The innovation of Ajax technology is that the traditional "request-wait-response-refresh-return data" mode is improved, and before the information is returned, users can continue their operations and the current page will not be refreshed because of the request. This greatly improves the interactivity.
Ajax is not really a technology, but it is made up of many technologies. One of the biggest features is the asynchronous transmission, the implementation of multithreaded services.
The asynchronous transmission of Ajax relies on the Xmlhttprequst object in JS, so we start with it.
XMLHttpRequest is an abstract object of the XMLHTTP build for data interaction. In IE, XMLHttpRequest as an ActiveX control, as a JS built-in object in FF Opera.
To create the encapsulation code for the XMLHttpRequest object:
Copy Code code 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 Properties:
0= Uninitialized 1 = Initialize 2 = Send Data 3 = 4 = complete in data transfer
ResponseText Properties:
1, 2=responsetext is an empty string 3 = receiving 4 = Receive complete
Responsexml Properties:
Once send () is executed, if you return the correct XML format data, you can use XMLHttpRequest to receive the returned data. Responsexml can format the return information as an XML Document object with a type of text/xml that returns null if it is not included.
Status property:
attribute Send (), the property status can be used to read the state of the object, only when ReadyState is 3 or 4, otherwise an error will occur when reading status. A few of the following are common:
100= customer must continue to issue request 200 = Transaction Success 400= Error Request 403 = Request not allowed 404 = no file found, query or URL 500= server Internal error 502= server is temporarily unavailable 505= server does not support or reject the HTTP version specified in the request header.
StatusText Properties:
After the Send () method, the transaction state is read through StatusText, StatusText returns the status line of the current HTTP request, and an error occurs only if the readystate is 3 4 o'clock.
onReadyStateChange Event:
The action to take when the value of this event property changes.
Abort () Method:
Stops a XMLHttpRequest object from requesting HTTP, restoring the object to its original state.
Open () Method:
Create a new HTTP request, and specify methods, URLs, and validation information, and so on, the syntax is: Xmlhttp.open (METHOD,URL,MODE,USER,PSD);
Method represents the request methods, with post, get, put, and so on, ignoring case. The URL is the destination address, mode is the type parameter, specifies whether the request is asynchronous, and the default is true.
When the open () method is called, the ReadyState property is set to 1.
Send () Method:
Xmlhttp.send (content) contents are to be sent, nothing can be ignored.
setRequestHeader () Method:
setRequestHeader (header, value) sets a single HTTP header information, and when readystate is 1 o'clock, this method can be called after open (), otherwise an exception will be returned, and the original will be overwritten if already exists. The value sample is a string of data that represents the value of the header name.
getResponseHeader () Method:
By reading the header information, you can read the Content-type (content type), content-length (content length), last-modify (last modified) date, etc., depending on the specific site.
getAllResponseHeaders () Method:
Get all the header information.
The next example is to get the header information:
Copy Code code as follows:

<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; Registering a 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>
<body>
<center>
<input type= "button" onclick= "Headrequst (' Content-type ')" value= "Content-type" ><br><br>
<input type= "button" onclick= "Headrequst (' Date ')" value= "Date" ><br><br>
<input type= "button" onclick= "Headrequst (' Connection ')" value= "Connection" ><br><br>
<input type= "button" onclick= "Headrequst (' All ')" value= "All Headers" ><br>
<br><br><br>
<span id= "state" ></span><br>
</center>
<body>

This example works well under IE, under the FF dead or alive out, MS Reason is FF does not support ActiveX ... Ask the expert to solve ... 囧rz
JSON
The full name of JSON is: the JavaScript Object Notation objects flag. It is a lightweight text-based and language-independent data Interchange format. Like XML, it's a text organization format, specifically, like we have a set of data, in XML:
<user>
<name>Dumpling</name> <gender>Famle</gender><age>22<age>
<user>
So if you use the JSON format, it's:
' User ': [{' Name ': ' Dumpling ', ' gender ': ' Famle ', ' age ': 22}]
The advantage is that it simplifies the parsing and storage of the acquired data.
If the above example is more complex, you can see the specific format of JSON, when we declare in JS, we can write this:
Copy Code code as follows:

var users={
"Users": [
{"Name": "Dumpling", "gender": "Famle", "Age": 22},
{"Name": "Sanday", "Gender": "Famle", "Age": 20},
{' name ': ' Shine ', ' Gender ': ' Famle ', ' Age ': 18}
]};

Using JSON to encapsulate data, you use a method of json.stringify (obj). Obj can encapsulate a class on its own.
We do not need to write the string ourselves, just give the value, and then use the function to encapsulate it. Here's a simple example:
Copy Code code as follows:

<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>
<body>
<center>
<form method= "POST" action= "#" name=jsonform>
<table border= "1" id= "NewUser" >
<tr>
<td>name: </td><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><td><input type= "text" name= "age" ></td>
</tr>
<tr>
&LT;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>

Fear is too long I cover up, anyway the result is such a drop:

Of course, if you want to encapsulate a lot of, such as the submission of 5 6 users and then packaged into a JSON format, you can put these several into a arry, and then the Arry as a stringify parameters can, try it yourself ~ I will not be on the code ~

parsing and assigning to JSON in JS

This is even the center of the JSON, the parsing of his is very simple, such as the previous example,

Copy Code code 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 I want to get sanday this value, you can write this: Var username=uersjson.users[1].name; This one, the other is no problem.
If you want to modify the data, it is directly assigned, such as I want to modify the price of the food userjson.objects[0].price=43;
As for judging whether the input is lawful or not, I am too lazy to write, it takes time.
JSON is here, the last part of the next.
Prototype framework
Let's take a look at prototype's website: http://www.prototypejs.org/
It is actually to JS done a lot of expansion, generally by the general method and template two parts of the composition. General methods such as $ () $$ () $A (), and so on, the template is to expand the JS internal class, and provide a variety of AJAX applications support templates. Specific you can give a look at the site. For two examples, please go to the API page to see more: http://api.prototypejs.org/(yes, I'm lazy ╮(╯▽╰)╭)
$ () method: Gets the Element object, similar to the getElementById method, and can accept multiple arguments, returning an array.
$$ () Method: Gets the specified array of elements, similar to the Getelementbytagname () method, and gets the object based on the label name.
Ajax objects: We also said just now, because the browser is different, we need to write a lot of judgment code, so prototype gave us, The Ajax.request object encapsulates the code that creates the XMLHttpRequest object, as well as a variety of common methods for handling server return information, so it is still useful. To further study, please continue to refer to the API link above (= =!)
Form object: Because it is very commonly used, so form is also prototype focus on the object, this part is very important, so you can refer to the relevant parts of the API ...

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.