Ajax articles
XmlDocument and XMLHttpRequest objects
First: Create the XMLHttpRequest Request Object
Copy Code code 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 Code code 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 that creates the XMLHttpRequest request object can be invoked.
Note: The XMLHTTP object is not a consortium standard, so you should consider the support of different browser environments when creating.
The XMLHTTP object has a total of 6 methods 8 properties that support two execution modes: synchronous and asynchronous.
List of properties and methods of the XMLHTTP object (from the Ixmlhttprequest Interface): Property name
Type
Describe
onReadyStateChange
N/A
Specifies the event handler function that is invoked when the ready state changes, only for asynchronous operations
ReadyState
Long
Status of the asynchronous operation: uninitialized (0), loading (1), Loaded (2), Interaction (3), completed (4)
Responsebody
Variant
Returns the body of the response message as a unsigned byte array
Responsestream
Variant
Returns the body of the response message as an ADO Stream object
ResponseText
String
Returns the body of the response message as a text string
Responsexml
Object
Resolves the body of the response message to a XmlDocument object through XMLDOM
Status
Long
HTTP status code returned by the server
StatusText
String
Server HTTP response row status
Method name
Describe
Abort
Cancel the current HTTP request
getAllResponseHeaders
Retrieving all header fields from the response information
getResponseHeader
Get an HTTP header field value from the body of the response message
Open (Method,url,boolasync,bstruser,bstrpassword)
Open a connection to the HTTP server
Send (Varbody)
Send a request to the HTTP server. can contain body text.
setRequestHeader (Bstrheader, Bstrvalue)
Set the header field for a request
Second: Send a request to the server
Sending a request to the server via the XMLHttpRequest object is very simple, and you just need to pass it a URL to the server page that will generate the 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);
}
}
When the request is set by the above code, control is returned to us immediately, while the network and the server are busy performing their own tasks.
Third: Use callback functions to monitor requests
We sent an asynchronous request to the server through the XMLHttpRequest object, so how do we know if the request has been completed? So the second part of processing asynchronous communication is to set an entry point in your code so that you can get the result information at the end of the call. This is usually done by assigning a callback function.
Callback functions are ideal for event-driven programming methods in most modern UI toolkits.
Here we rewrite the SendRequest () function as follows:
Copy Code code as follows:
var req=null; Declaring 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. This is done by customizing the JavaScript function onreadystatechange () for event handling.
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 handle the response information received from the server.
View sourceprint?01 function onreadystatechange () {
var data=null;
if (req.readystate==4) {
04
if (req.status==200) {
Data=req.responsetext;
Modified} else {
Data= "Loading ..... ["+req.readstate+"] ";
09}
10
11}
12.. Here you can do some operations related to this return information, such as output information.
13}
The ResponseText property of the XMLHttpRequest object is used in the preceding code to get the data in the response as 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 property. If the MIME type of the response has been correctly set to Text/xml, this property returns a DOM document, so we can use the properties and functions of the DOM (such as getElementById () and childnodes) to process it.
JQuery Ajax Chapter
Jquery.ajax (options): Load remote Data via HTTP request
The underlying AJAX implementation of JQuery. $.ajax () returns the XMLHttpRequest object that it created. In most cases you do not need to manipulate the object directly, but in special cases you can use it to manually terminate the request. $.ajax () has only one option parameter: The parameter Key/value object, which contains the configuration and callback function information. Detailed parameter options see below. Name of parameter
Type
Describe
Url
String
(Default: Current page address) sends the requested address.
Type
String
(Default: "Get") Request method ("POST" or "get"), default to "get". Note: Other HTTP request methods, such as put and DELETE, are also available, but only partially supported by browsers.
Timeout
Number
Sets the request timeout (in milliseconds). This setting overrides the global setting.
Async
Boolean
(Default: TRUE) The default setting is that all requests are asynchronous requests. If you need to send a sync request, set this option to false. Note that the synchronization request will lock the browser and the user's other actions must wait for the request to complete before it can be executed.
Beforesend
Function
You can modify the functions of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. The XMLHttpRequest object is the only parameter.
function (XMLHttpRequest) {
This The options for this AJAX request
}
Cache
Boolean
(default: TRUE) JQuery 1.2 new functionality, set to false will not load request information from the browser cache.
Complete
Function
The callback function (called when the request succeeds or fails) after the request completes. Parameters: XMLHttpRequest Object, Success message string.
function (XMLHttpRequest, textstatus) {
This The options for this AJAX request
}
ContentType
String
(Default: "application/x-www-form-urlencoded") the content encoding type when sending information to the server. Default values are appropriate for most applications.
Data
Object,
String
Data sent to the server. is automatically converted to the request string format. The GET request is appended to the URL. View the ProcessData option description to prevent this automatic conversion. Must be in the Key/value format. If you are an array, JQuery will automatically correspond to the same name for different values. Such as:
{foo:["bar1", "Bar2"]} is converted to ' &foo=bar1&foo=bar2 '.
DataType
String
The type of data expected to be returned by the server. If not specified, JQuery will automatically return Responsexml or responsetext based on the HTTP packet MIME information and pass as a callback function parameter, available values:
"XML": Returns an XML document that can be processed with jQuery.
HTML: Returns plain text HTML information, including script elements.
Script: Returns the plain text JavaScript code. Results are not automatically cached.
"JSON": Returns JSON data.
"JSONP": Jsonp format. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? To the correct function name to execute the callback function.
Error
Function
(Default: Automatic judgment (XML or HTML)) This method is called when a request fails. This method has three parameters: the XMLHttpRequest object, the error message, and (possibly) the error object being caught.
function (XMLHttpRequest, textstatus, Errorthrown) {
Typically, only one of the Textstatus and Errorthown has a value.
This The options for this AJAX request
}
Global
Boolean
(default: TRUE) triggers a global AJAX event. 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) gets new data only when the server data changes. Use HTTP packet last-modified header information to determine.
ProcessData
Boolean
(default: TRUE) by default, the data sent is 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 do not want to convert.
Success
Function
callback function after successful request. This method has two parameters: the server returns the data, returns the status
function (data, textstatus) {
Data could be xmldoc, jsonobj, HTML, text, etc ...
This The options for this AJAX request
}
This here in the Ajax event is the option information that points to the AJAX request.
Jquery.ajaxsetup (Options): Sets the global AJAX default option.
such as: Set AJAX request default address is "/xmlhttp/", prohibit the triggering of global Ajax events, using POST instead of the default get method. Subsequent AJAX requests no longer have any option parameters set. Its sample code:
$.ajaxsetup ({
URL: "/xmlhttp/",
Global:false,
Type: "POST"
});
$.ajax ({data:mydata});
Serialize () and Serializearray ()
Serialize (): Sequence table table contents are strings.
Serializearray (): Serializes the Table element (similar to the '. Serialize () ' method) to return the JSON data structure.
The underlying implementation of the jquery Ajax above, which we rarely use, is encapsulated by jquery for Jquery.ajax (), making it easier to use AJAX for asynchronous invocation.
1. Load (URL, [data], [callback]): Loads the remote HTML file code and inserts it into the DOM.
URL (String): The URL address of the requested HTML page.
Data (MAP): (optional parameters) sent to the server's key/value.
Callback (callback): (optional parameter) a callback function that does not need to be success when the request completes.
This method is passed by default using Get method, and is automatically converted to post if the [data] parameter is passed in. 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. Syntax is like "URL #some > selector".
This method makes it easy to dynamically load some HTML files, such as forms.
2. Jquery.get (URL, [data], [callback]): Asynchronous request using Get method
URL (String): The URL address where the request is sent.
Data (MAP): (optional) The information to be sent to the server, expressed as a Key/value key-value pair, is appended to the request URL as a querystring.
Callback (function): (optional) the callback function (which is invoked only if the response return state is success) when loading succeeds.
3. Jquery.post (URL, [data], [callback], [Type]): Asynchronous request using POST method
URL (String): The URL address where the request is sent.
Data (MAP): (optional) The information to be sent to the server, expressed as a Key/value key-value pair.
Callback (function): (optional) the callback function (which is invoked only if the response return state is success) when loading succeeds.
Type (String): (optional) The official description is: type of data to is sent. The type that should actually be requested for the client (Json,xml, etc.)
If you set the requested format to "JSON", you are not setting the Response back ContentType as: Response.ContentType = "Application/json"; Then you will not be able to capture the returned data.
4. Jquery.getscript (URL, [callback]): Load and execute a JavaScript file with a Get-mode request.
URL (String): The JS file address is to be loaded.
Callback (function): (optional) After successfully loading the callback function.
Before the JQuery 1.2 version, Getscript can only invoke the same domain JS file. 1.2, you can invoke JavaScript files across domains. Note: Safari 2 or earlier cannot execute scripts synchronously in the global scope. If you add a script by getscript, add the delay function.
This method can be used for example, when only the editor focus () to load the editor required JS files.