Home  >  Article  >  Web Front-end  >  JavaScript Advanced Chapter 3 Introduction to Ajax, JSON, and Prototype_Basic Knowledge

JavaScript Advanced Chapter 3 Introduction to Ajax, JSON, and Prototype_Basic Knowledge

WBOY
WBOYOriginal
2016-05-16 17:55:211094browse
Ajax
I have heard this word a lot, but I have never really been exposed to it, so I will learn a little bit about it here.
The innovation of Ajax technology is that it improves the traditional "request-wait-response-refresh-return data" mode. Users can continue their operations before the information is returned, and the current page will not be refreshed due to the request. This greatly improves interactivity.
Ajax is not actually a technology, but consists of many technologies. One of the biggest features is that it can be transmitted asynchronously to realize multi-threaded services.
Ajax’s asynchronous transmission relies on the XMLHttpRequst object in js, so we start with it.
XMLHttpRequest is an abstract object formed by XMLHttp and is used for data interaction. In IE, XMLHttpRequest is used as an ActiveX control and in FF Opera as a built-in js object.
Create the encapsulation code of the XMLHttpRequest object:
Copy the code The 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");
}
}


ReadyState attribute:
0=Not initialized 1=Initialized 2=Sending data 3=Data transfer in progress 4=Complete
responseText attribute:
1, 2=responseText is a null character String 3 = Receiving 4 = Receiving completed
responseXML attribute:
After executing send(), if the correct xml format data is returned, XMLHttpRequest can be used to receive the returned data. responseXML can format the return information as an XML Document object, the type is text/xml. If it does not contain it, it will return null.
status attribute:
After attribute send(), you can use the attribute status to receive and read the status of things. This attribute can only be used when ReadyState is 3 or 4, otherwise an error will occur when reading status. Common ones are as follows:
100=The client must continue to make the request 200=Transaction successful 400=Bad request 403=Request not allowed 404=No file, query or URL found 500=Internal server error 502=The server is temporarily unavailable 505=The server does not support or rejects the HTTP version specified in the request header.
statusText attribute:
After the send() method, read the transaction status through statusText. statusText returns the status line of the current HTTP request. This attribute can only be used when readyState is 3 4, otherwise an error occurs.
onreadystatechange event:
The operation to be performed when the attribute value of this event 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 verification information, etc. The syntax is: xmlHttp.open(method,url,mode,user,psd);
method Indicates the request method, including post, get, put, etc., ignoring case. url is the destination address, mode is a non-two type parameter, specifying whether the request is asynchronous, and the default is true.
After calling the open() method, the readyState attribute is set to 1.
send() method:
xmlHttp.send(content); content is the content to be sent and can be ignored if there is no content.
setRequestHeader() method:
setRequestHeader(header, value) sets a single HTTP header information. When readyState is 1, this method can be called after open(), otherwise an exception will be returned if it already exists. The original one will be overwritten. The value type is a string type data representing 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, etc., according to the specific Websites are different.
getAllResponseHeaders() method:
Get all header information.
The next example is to get the header information:
Copy the code The code is as follows:



Ajax test

























这个例子在IE下工作很顺利,在FF下死活出不来,MS原因是FF不支持ActiveX。。。求高手解决下。。。囧rz
JSON
JSON的全称是:javascript object notation 对象标志。它是一种轻量级的基于文本并且和语言无关的数据交换格式。和XML类似,是一种文本组织格式,具体是这样的,比如我们有一组数据,用xml的话:

Dumpling Famle22

那么如果用JSON的格式,就是:
"user":[{"name":"Dumpling", "gender":"Famle", "age":22}]
优点就是它可以简化获取的数据的解析和存储等工作。
如果上面的例子再写复杂一点,就可以看到JSON的具体格式了,我们在JS中声明的时候,就可以这么写:
复制代码 代码如下:

var users={
"users":[
{"name":"Dumpling", "gender":"Famle", "age":22},
{"name":"Sanday", "gender":"Famle", "age":20},
{"name":"Shine", "gender":"Famle", "age":18}
]};

使用JSON封装数据,用到的是JSON.stringify(obj)的方法。obj自己封装一个类就可以。
不需要我们自己来写字符串,只要给值,然后用函数封装就可以了。来个简单的例子:
复制代码 代码如下:



testing















Name: Gender:
Age:





NameGenderAge





害怕太长我就遮起来了,反正结果是这样子滴:

 

当然,如果要一次封装很多,比如提交了5 6个用户然后一次封装成JSON格式,可以把这几个放到一个Arry里,然后把arry作为stringify的参数就可以,自己试一下吧~我就不上代码了~

在JS中对JSON解析和赋值

这一块就算是json的中心了,对他的解析其实很简单的,比如还是之前的例子,

复制代码 代码如下:

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}
]
};

Then if I want to get the value of sanday, I can write like this: var username=uersJson.users[1].name; Once you know this, everything else will be fine~
If you want to modify the data, then Just assign the value directly. For example, if I want to modify the price of that food userJson.objects[0].price=43;
As for judging whether the input is legal, I am too lazy to write it, which is time-consuming.
That’s it for JSON, now comes the last part.
Prototype framework
First go to the prototype website: http://www.prototypejs.org/
It actually makes a lot of expansions to JS , which is roughly composed of two parts: general methods and templates. Common methods such as $() $$() $A(), etc., while templates extend JS internal classes and provide support templates for various Ajax applications. For details, you can check out the website given. Here are two examples, please go to the API page for more: http://api.prototypejs.org/ (Yes, I am very lazy╮(╯▽╰)╭)
$() method: Get the element object, similar For the getElementById method, it can accept multiple parameters and return an array.
$$() method: Get the specified element array, similar to the getElementByTagName() method, get the object based on the tag name.
Ajax object: As we just said, because browsers are different, we need to write a lot of judgment code, so the prototype does it for us. The Ajax.Request object encapsulates the code for creating the XMLHttpRequest object, as well as various processing It is a common method for the server to return information, so it is still very useful. If you want to learn more, please continue to refer to the API link above (= =!)
Form object: Because it is really commonly used, form is also the object that prototype focuses on. This part is very important, so you can refer to the API. part. . . . . .
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn