Ajax article
XMLDocument and XMLHttpRequest objects
First: Create XMLHttpRequest request object
function getXMLHttpRequest() {
var xRequest=null;
if(window.XMLHttpRequest) {
xRequest=new XMLHttpRequest();
}else if(typeof ActiveXObject != "undefined"){
xRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
return xRequest;
}
Or:
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 that creates an XMLHttpRequest request object can be called.
Note: The XMlHTTP object is not a W3C standard, so the support of different browser environments must be considered when creating it.
The XMLHTTP object has a total of 6 methods and 8 attributes, and supports two execution modes: synchronous and asynchronous.
List of attributes and methods of XMLHTTP object (from IXMLHTTPRequest interface): Attribute name
Type
Description
onreadystatechange
N/A
Specifies the event handler to be called when the ready state changes Function, only for asynchronous operations
readyState
Long
Status of asynchronous operations: Uninitialized (0), Loading (1), Loaded (2), Interactive (3), Completed (4 )
responseBody
Variant
Return the response message body as an unsigned byte array
responseStream
Variant
Return the response message body as an ADO Stream object
responseText
String
Return the response message body as a text string
responseXML
Object
Parse the response message body into an XMLDocument object through XMLDom
status
Long
HTTP status returned by the server Code
statusText
String
Server HTTP response line status
Method name
Description
abort
Cancel the current HTTP request
getAllResponseHeaders
Retrieve all from the response information The header field
getResponseHeader
Gets an HTTP header field value from the response message body
open(method,url,boolAsync,bstrUser,bstrPassword)
Opens a connection with the HTTP server
send (varBody)
Sends a request to the HTTP server. Can contain body text.
setRequestHeader(bstrHeader, bstrValue)
Set the header field of a request
Second: Send a request to the server
Sending a request to the server through the XMLHttpRequest object is very simple, just pass it a server The URL of the page that 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, control will be returned to us immediately. At the same time, the network and server are busy performing their own tasks.
Third: Use callback function to monitor requests
We send an asynchronous request to the server through the XMLHttpRequest object, so how do we know that the request has been completed? So the second part of handling asynchronous communication is to set up an entry point in the code so that the result information can be obtained at the end of the call. This is usually accomplished by assigning a callback function.
Callback functions are ideally suited for the event-driven programming approach found in most modern UI toolboxes.
Below we rewrite the sendRequest() function as follows:
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. Specifically, event processing is performed through the custom Javascript function onReadyStateChange().
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 .....Here you can do some operations related to the returned information, such as outputting information, etc.
13 }
The responseText attribute of the XMLHttpRequest object is used in the above code to obtain the 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 data set, we can use the responseXML attribute. If the response's MIME type has been set correctly to text/xml, this property will return a DOM document, so we can use DOM properties and functions (such as getElementById() and childNodes) to process it.
JQuery Ajax
jQuery.ajax( options ): Load remote data through HTTP requests
The underlying AJAX implementation of jQuery. $.ajax() returns the XMLHttpRequest object it created. In most cases you will not need to manipulate this object directly, but in special cases it can be used to manually terminate the request. $.ajax() has only one option parameter: parameter key/value object, including each configuration and callback function information. See detailed parameter options below. Parameter name
Type
Description
url
String
(default: current page address) The address to send the request.
type
String
(default: "GET") request method ("POST" or "GET"), default 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 (milliseconds). This setting overrides the global setting.
async
Boolean
(Default: true) By default, all requests are asynchronous requests. If you need to send synchronous requests, set this option to false. Note that a synchronous request will lock the browser, and the user must wait for the request to complete before other operations can be performed.
beforeSend
Function
Function that can modify the XMLHttpRequest object before sending the request, such as adding custom HTTP headers. The XMLHttpRequest object is the only parameter.
function (XMLHttpRequest) {
this; // the options for this ajax request
}
cache
Boolean
(default: true) jQuery 1.2 new function, set to false Request information will not be loaded from the browser cache.
complete
Function
Callback function after the request is completed (called when the request succeeds or fails). Parameters: 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 suitable for most applications.
data
Object,
String
Data sent to the server. Will be automatically converted to request string format. Appended to the URL in GET requests. See the processData option description to disable this automatic conversion. Must be in Key/Value format. If it is an array, jQuery will automatically assign the same name to different values. For example:
{foo:["bar1", "bar2"]} is converted to '&foo=bar1&foo=bar2'.
dataType
String
The data type expected to be returned by the server. If not specified, jQuery will automatically return responseXML or responseText based on the HTTP package MIME information and pass it as a callback function parameter. Available values:
"xml": Returns an XML document that can be processed by jQuery.
"html": Returns plain text HTML information; contains script elements.
"script": Returns plain text JavaScript code. Results are not automatically cached.
"json": Returns JSON data.
"jsonp": JSONP format. When calling a function using JSONP format, such as "myurl?callback=?" jQuery will automatically replace ? with the correct function name to execute the callback function.
error
Function
(Default: automatic judgment (xml or html)) This method will be called when the request fails. This method takes three parameters: the XMLHttpRequest object, the error message, and (possibly) the captured error object.
function (XMLHttpRequest, textStatus, errorThrown) {
// Usually only one of textStatus and errorThown has a value
this; // the options for this ajax request
}
global
Boolean
(Default: true) Whether to trigger global AJAX events. Setting to false will not trigger global AJAX events such as ajaxStart or ajaxStop. Can be used to control different Ajax events
ifModified
Boolean
(Default: false) Only get new data when the server data changes. Use HTTP packet Last-Modified header information to determine.
processData
Boolean
(default: true) By default, the data sent will be converted to an object (technically not a string) to match the default content type "application/x-www-form- urlencoded". Set to false if you want to send DOM tree information or other information that you don't want to convert.
success
Function
Callback function after the request is successful.This method has two parameters: the server returns data and returns status
function (data, textStatus) {
// data could be xmlDoc, jsonObj, html, text, etc...
this; // the options for this ajax request
}
This in the Ajax event here all points to the option information of the Ajax request.
jQuery.ajaxSetup( options ): Set global AJAX default options.
For example: set the default address of AJAX requests to "/xmlhttp/", prohibit triggering global AJAX events, and use POST instead of the default GET method. Subsequent AJAX requests will not set any option parameters. Its 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 '.serialize()' method) and return JSON data structure data.
The above underlying implementation of JQuery Ajax is rarely used by us. JQuery encapsulates jQuery.ajax(), allowing us to use Ajax asynchronous calls more easily.
1. load( url, [data], [callback] ): Load the remote HTML file code and insert it into the DOM.
url (String): URL address of the requested HTML page.
data (Map): (optional parameter) key/value data sent to the server.
callback (Callback): (optional parameter) The callback function when the request is completed (does not need to be successful).
This method uses the GET method by default. If the [data] parameter has data passed in, it will be automatically converted to the POST method. In jQuery 1.2, you can specify a selector to filter the loaded HTML document, and only the filtered HTML code will be inserted into the DOM. The syntax is "url #some > selector".
This method can easily dynamically load some HTML files, such as forms.
2. jQuery.get( url, [data], [callback] ): Use GET method to make asynchronous requests
url (String): URL address to send the request.
data (Map): ( Optional) The data to be sent to the server, expressed in the form of Key/value pairs, will be appended to the request URL as QueryString.
callback (Function): (optional) Callback function when loading is successful (this method is called only when the return status of Response is success).
3. jQuery.post( url, [data], [callback], [type] ): Use POST method to make asynchronous requests
url (String): The URL address to send the request.
data ( Map): (optional) The data to be sent to the server, expressed in the form of Key/value pairs.
callback (Function): (optional) Callback function when loading is successful (this method is called only when the return status of Response is success).
type (String): (optional) The official description is: Type of data to be sent. In fact, it should be the type requested by the client (JSON, XML, etc.)
If you set the request format to "json", at this time you have not set the ContentType returned by Response to: Response.ContentType = "application/json "; then you won't be able to capture the returned data.
4. jQuery.getScript( url, [callback] ): Request to load and execute a JavaScript file through GET method.
url (String): The address of the JS file to be loaded.
callback (Function): (optional) Callback function after successful loading.
Before jQuery 1.2, getScript could only call JS files in the same domain. In 1.2, you can call JavaScript files across domains. Note: Safari 2 or earlier cannot execute scripts synchronously in the global scope. If you add a script via getScript, please add a delay function.
This method can be used, for example, to load the JS files required by the editor when only the editor is focus().