Learning from Ajax to JQuery Ajax

Source: Internet
Author: User
Tags getscript

Ajax
XMLDocument and XMLHttpRequest objects
1. Create an XMLHttpRequest request object

Copy codeThe Code is as follows: function getXMLHttpRequest (){
Var xRequest = null;
If (window. XMLHttpRequest ){
XRequest = new XMLHttpRequest ();
} Else if (typeof ActiveXObject! = "Undefined "){
XRequest = new ActiveXObject ("Microsoft. XMLHTTP ");
}
Return xRequest;
}

Or:Copy codeThe Code is as follows: var request = null;
Function createRequest (){
Try {
Request = new XMLHttpRequest (); // non-Microsoft IE browser
} Catch (trymicrosoft) {// Microsoft IE
Try {
Request = new ActiveXObject ("Msxml2.XMLHTTP ");
} Catch (othermicrosoft ){
Try {
Request = new ActiveXObject ("Microsoft. XMLHTTP ");
} Catch (failed ){
Request = null;
}
}
}
If (request = null)
Alert ("Error creating request object !");
}
[Code]
This independent function for creating the XMLHttpRequest request object can be called.
Note: XMlHTTP objects are not W3C standards. Therefore, you must consider the support of different browser environments when creating them.
The XMLHTTP object has 6 methods and 8 attributes. It supports two execution modes: synchronous and asynchronous.
XMLHTTP object attribute and method list (from IXMLHTTPRequest Interface): attribute name
Type
Description
Onreadystatechange
N/
Specifies the event processing function called when the ready status changes. It is only used for asynchronous operations.
ReadyState
Long
Asynchronous Operation Status: Not initialized (0), loading (1), loaded (2), InterAction (3), completed (4)
ResponseBody
Variant
Returns the response body as an unsigned byte array.
ResponseStream
Variant
Returns the response body as an ADO Stream object.
ResponseText
String
Returns the response body as a text string.
ResponseXML
Object
Resolve the response body to an XMLDocument object through XMLDom
Status
Long
HTTP status code returned by the server
StatusText
String
Server HTTP Response line status
Method Name
Description
Abort
Cancel current HTTP Request
GetAllResponseHeaders
Retrieve all header fields from the response information
GetResponseHeader
Obtain an HTTP header field value from the response body.
Open (method, url, boolAsync, bstrUser, bstrPassword)
Open a connection to the HTTP server
Send (varBody)
Send a request to the HTTP server. Body.
SetRequestHeader (bstrHeader, bstrValue)
Set the header field of a request
2. send a request to the server
It is very easy to send a request to the server through the XMLHttpRequest object. You only need to pass it the URL of a server page, which will generate data.
[Code]
Function sendRequest (url, params, HttpMethod ){
If (! HttpMethod ){
HttpMethod = "POST ";
}
Var req = getXMLHttpRequest ();
If (req ){
Req. open (HttpMethod, url, true );
Req. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
Req. send (params );
}
}

After setting the request through the above Code, the control will be immediately returned to us, while the network and server are busy executing their own tasks.
Third: Use callback functions to monitor requests
Through the XMLHttpRequest object, we send an asynchronous request to the server. How can we know that the request has been completed? Therefore, the second part of asynchronous communication processing is to set an entry point in the Code so that the result information can be obtained at the end of the call. This is usually done by allocating a callback function.
Callback functions are ideal for event-driven programming methods in most modern UI toolboxes.
The sendRequest () function is rewritten as follows:Copy codeCode: var req = null; // declare a global variable
Function sendRequest (url, params, HttpMethod ){
If (! HttpMethod ){
HttpMethod = "GET ";
}
Req = getXMLHttpRequest ();
If (req ){
Req. onreadystatechange = onReadyStateChange; // note that this is the onreadystatechange callback function used to monitor requests. The custom Javascript function onReadyStateChange () is used to process events.
Req. open (HttpMethod, url, true );
Req. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
Req. send (params );
}
}

The following callback function onReadyStateChange is used to process the response information obtained from the server.
View sourceprint? 01 function onReadyStateChange (){
02 var data = null;
03 if (req. readyState = 4 ){
04
05 if (req. status = 200 ){
06 data = req. responseText;
07} else {
08 data = "loading... [" + req. readState + "]";
09}
10
11}
12... you can perform operations related to the returned information, such as output information.
13}
The above Code uses the responseText attribute of the XMLHttpRequest object to obtain data in the response in the form of a text string. This is useful for simple data. When we need the server to return a larger structured dataset, we can use the responseXML attribute. If you have correctly set the response MIME type to text/xml, this property will return a DOM document, so we can use DOM attributes and functions (such as getElementById () and childNodes) to process it.
JQuery Ajax
JQuery. ajax (options): loads remote data through HTTP requests
JQuery's underlying AJAX implementation. $. Ajax () returns the created XMLHttpRequest object. In most cases, you do not need to directly operate on this object, but in special cases it can be used to manually terminate the request. $. Ajax () has only one option parameter: The parameter key/value object, which contains information about various configurations and callback functions. For detailed Parameter options, see. Parameter Name
Type
Description
Url
String
(Default: Current page address) the address of the request sent.
Type
String
(Default: "GET") Request Method ("POST" or "GET"). The default value is "GET ". Note: Other HTTP request methods, such as PUT and DELETE, can also be used, but are only supported by some browsers.
Timeout
Number
Set the request timeout (in milliseconds ). This setting overwrites the global setting.
Async
Boolean
(Default: true) by default, all requests are asynchronous requests. To send a synchronization request, set this option to false. Note: The synchronous request locks the browser. Other operations can be performed only after the request is completed.
BeforeSend
Function
Before sending a request, you can modify the function of the XMLHttpRequest object, for example, adding a custom HTTP header. The XMLHttpRequest object is a unique parameter.
Function (XMLHttpRequest ){
This; // the options for this ajax request
}
Cache
Boolean
(Default: true) New jQuery 1.2 function. setting this parameter to false will not load request information from the browser cache.
Complete
Function
Callback Function after the request is complete (called when the request is successful or fails ). Parameter: XMLHttpRequest object, success information string.
Function (XMLHttpRequest, textStatus ){
This; // the options for this ajax request
}
ContentType
String
(Default: "application/x-www-form-urlencoded") Content Encoding type when sending information to the server. The default value is applicable to most applications.
Data
Object,
String
The data sent to the server. Will be automatically converted to the request string format. The GET request will be appended to the URL. View the description of the processData option to disable automatic conversion. It must be in Key/Value format. If it is an array, jQuery automatically corresponds to the same name for different values. For example:
{Foo: ["bar1", "bar2"]} is converted to '& foo = bar1 & foo = bar2 '.
DataType
String
Expected data type returned by the server. If this parameter is not specified, jQuery will automatically return responseXML or responseText Based on the MIME information of the HTTP package and pass it as a callback function parameter. Available values:
"Xml": returns an XML document, which can be processed by jQuery.
"Html": returns plain text HTML information, including script elements.
"Script": returns plain text JavaScript code. Results are not automatically cached.
"Json": Return JSON data.
"Jsonp": JSONP format. When calling a function in the form of JSONP, such as "myurl? Callback =? "Will jQuery be replaced automatically? For the correct function name to execute the callback function.
Error
Function
(Default: automatically determines (xml or html) This method is called when a request fails. This method has three parameters: XMLHttpRequest object, error message, and (possibly) captured error object.
Function (XMLHttpRequest, textStatus, errorThrown ){
// Generally, textStatus and errorThown have only one value.
This; // the options for this ajax request
}
Global
Boolean
(Default: true) Whether to trigger a global AJAX event. Setting false does not trigger global AJAX events, such as ajaxStart or ajaxStop. Can be used to control different Ajax events
IfModified
Boolean
(Default: false) obtain new data only when the server data changes. Use the Last-Modified header information of the HTTP packet to determine.
ProcessData
Boolean
(Default: true) by default, data sent is converted to an object (technically not a string) with the default content type "application/x-www-form-urlencoded ". If you want to send the DOM tree information or other information that does not want to be converted, set it to false.
Success
Function
Callback Function after successful request. This method has two parameters: the server returns data and returns the status.
Function (data, textStatus ){
// Data cocould be xmlDoc, jsonObj, html, text, etc...
This; // the options for this ajax request
}
Here, this in the Ajax event points to the options of the Ajax request.
JQuery. ajaxSetup (options): sets the global AJAX default options.
For example, set the default address of an AJAX request to "/xmlhttp/". Do not trigger a global AJAX event. Use POST instead of the default GET method. No option parameters are set for subsequent AJAX requests. Sample Code:
$. AjaxSetup ({
Url: "/xmlhttp /",
Global: false,
Type: "POST"
});
$. Ajax ({data: myData });
Serialize () and serializeArray ()
Serialize (): the content of the sequence table is a string.
SerializeArray (): serialize table elements (similar to the '. serialize ()' method) to return JSON data structure data.
The underlying implementation of JQuery Ajax is rarely used. JQuery encapsulates jQuery. ajax (), making it easier to use Ajax asynchronous calls.
1. load (url, [data], [callback]): load the remote HTML file code and insert it into the DOM.
Url (String): the URL of the requested HTML page.
Data (Map): (optional) key/value data sent to the server.
Callback (Callback): (optional) callback function when the request is completed (success is not required.
By default, this method uses the GET method to pass data. If the [data] parameter passes data in, it is automatically converted to the POST method. In jQuery 1.2, you can specify a selector to filter loaded HTML documents. In DOM, only filtered HTML code is inserted. The syntax is like "url # some> selector ".
This method can easily dynamically load HTML files, such as forms.
2. jQuery. get (url, [data], [callback]): Use the GET Method for asynchronous requests.
Url (String): the URL of the request.
Data (Map): (optional) data to be sent to the server, which is expressed in Key/value pairs and will be appended to the request URL as QueryString.
Callback (Function): (optional) callback Function when the load is successful (this method is called only when the Response returns success ).
3. jQuery. post (url, [data], [callback], [type]): Use the POST method for asynchronous requests.
Url (String): the URL of the request.
Data (Map): (optional) data to be sent to the server, expressed in Key/value pairs.
Callback (Function): (optional) callback Function when the load is successful (this method is called only when the Response returns success ).
Type (String): (optional) the official description is: Type of data to be sent. In fact, it should be the client request type (JSON, XML, and so on)
If you set the request format to "json", you have not set the ContentType returned by Response to: Response. contentType = "application/json"; then you cannot capture the returned data.
4. jQuery. getScript (url, [callback]): request to load and execute a JavaScript file in GET mode.
Url (String): the url of the JS file to be loaded.
Callback (Function): (optional) callback Function after successful loading.
Before jQuery 1.2, getScript can only call JS files in the same domain. 1.2, you can call JavaScript files across domains. Note: Safari 2 or earlier versions cannot execute scripts simultaneously in the global scope. If you use getScript to add a script, add the latency function.
This method can be used to load the JS files required by the editor only when the editor focus () is used.

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.