1, a brief introduction to Ajax
AJAX = Asynchronous JavaScript and XML (asynchronous JavaScript and XML).
AJAX is not a new programming language, but a new method of using existing standards.
AJAX is the art of exchanging data and updating portions of a Web page with the server, without loading the entire page again.
2, what is AJAX? AJAX = asynchronous JavaScript and XML.
AJAX is a technique for creating high-speed, dynamic Web pages.
AJAX enables Web pages to be updated asynchronously by exchanging small amounts of data with the server in the background. This means that you can update a part of a webpage without having to load the entire page again.
Traditional Web pages (without AJAX) assume that you need to update the content, and you must reload the entire page surface.
There are a lot of examples of applications that use AJAX: Sina Weibo, Google maps, Renren, Youku and more.
The basic principle of 3,ajax
XMLHttpRequest is the basis of AJAX.
XMLHttpRequest objects all modern browsers support XMLHttpRequest objects (IE5 and IE6 use ActiveXObject).
XMLHttpRequest is used to exchange data with the server in the background. This means that you can update a part of a webpage without having to load the entire page again.
The creation of the XMLHttpRequest object:
var xmlhttp;
if (window. XMLHttpRequest)
{//code for ie7+, Firefox, Chrome, Opera, Safari
Xmlhttp=new XMLHttpRequest ();
}
Else
{//code for IE6, IE5
Xmlhttp=new ActiveXObject ("Microsoft.XMLHTTP");
}
Ajax requests
The XMLHttpRequest object is used to exchange data with the server.
Send request to Server
To send the request to the server, we use the open () and send () methods of the XMLHttpRequest object:
Xmlhttp.open ("GET", "Test1.txt", true);
Xmlhttp.send ();
Method
|
Descriptive narrative |
Open (Method,url,async) |
Specifies the type of request, the URL, and whether the request is processed asynchronously. Method: type of request; GET or POST URL: The location of the file on the server Async:true (asynchronous) or false (synchronous) |
Send (String) |
Sends the request to the server. String: Only for POST requests |
Ajax response
Server response
To obtain a response from the server, use the ResponseText or Responsexml property of the XMLHttpRequest object.
Property |
Descriptive narrative |
ResponseText |
Gets the response data in the form of a string. |
Responsexml |
Get the response data in XML form. |
Such as:
Xmlhttp.responsetext;
Xmlhttp.responsexml;
Ajax Processing:
onReadyStateChange Events
When a request is sent to the server, we need to run some response-based tasks.
The onreadystatechange event is triggered whenever the readyState changes.
The ReadyState attribute holds state information for XMLHttpRequest.
The following are three important properties of the XMLHttpRequest object:
Property |
Descriptive narrative |
onReadyStateChange |
The function (or function name) is called whenever the ReadyState property is changed. |
ReadyState |
The state of being xmlhttprequest. Vary from 0 to 4. 0: Request not initialized 1:server Connection established 2: Request received 3: In Request processing 4: The request is complete and the response is ready |
Status |
$: "OK" 404: Page Not Found |
In the onReadyStateChange event, we specify the task that is run when the server responds to readiness to be processed.
When ReadyState equals 4 and the status is 200, the response is ready:
Xmlhttp.onreadystatechange=function ()
{
if (xmlhttp.readystate==4 && xmlhttp.status==200)
{
Xmlhttp.responsetext; The results of the return are processed;
}
}
4,jquery Ajax (API from jquery 1.10)
Query.ajax (url,[settings]) Overview
Load remote Data over an HTTP request.
JQuery underlying AJAX implementations. Easy to use high-level implementation see $.get, $.post and so on. $.ajax () returns the XMLHttpRequest object that it created. In most cases you do not need to manipulate the function directly unless you need to manipulate the infrequently used options for a lot of other flexibility.
In the simplest case, the $.ajax () can be used directly without any parameters.
note that all options can be set globally through the $.ajaxsetup () function.
callback function
Suppose you want to handle the data obtained by $.ajax (), you need to use a callback function. Beforesend, error, Datafilter, success, complete.
- Beforesend is called before the request is sent, and a xmlhttprequest is passed in as a parameter.
- Error is called when the request is faulted. Incoming XMLHttpRequest object, describing a string describing the type of error and an exception object (if any)
- Datafilter is called after the request succeeds. The value returned by the incoming data and the "DataType" parameter. And you must return the new data (possibly processed) to the success callback function.
- Success called after the request. The data after the incoming return, and a string that includes the success code.
- Complete the function is called after the request has been completed, regardless of success or failure. The incoming XMLHttpRequest object, and a string that includes a success or error code.
Data type
The $.ajax () function relies on information provided by the server to process the returned data. Assuming that the server reports that the returned data is XML, the returned result can be traversed using either a normal XML method or a jquery selector. Assuming that other types, such as HTML, are available, the data is treated in textual form.
The datatype option also allows you to specify different data processing methods. In addition to simple XML, you can also specify HTML, JSON, JSONP, script, or text.
The data returned by the text and XML types is not processed. The data simply passes the XMLHttpRequest responsetext or Responsehtml property to the success callback function,
' Note ', we must make sure that the MIME type reported by the Web server matches the datatype we have chosen. For example, XML, the server side must declare Text/xml or Application/xml to obtain consistent results.
Assuming that the HTML type is specified, whatever embedded JavaScript will run before HTML is returned as a string. Similarly, if the script type is specified, the server-side generation JavaScript is run first, and then the scripts are returned as text data.
Assuming that the JSON type is specified, the obtained data is parsed as a JavaScript object, and the constructed object is returned as a result. To achieve this, he first tried to use Json.parse (). If the browser does not support it, use a function to build it. JSON data is a structured data that can be easily parsed by JavaScript. Assuming that the obtained data file resides on the remote server (the domain name is different, that is, the data is obtained across domains), you need to use the JSONP type. With such a type, a query string callback= is created? , this number is appended to the URL of the request. The server side should precede the JSON data with a callback function name in order to complete a valid JSONP request. Suppose you want to specify the parameter name of the callback function in place of the default callback, by setting the Jsonp of the $.ajax ().
Note that Jsonp is an extension in JSON format. He requires some server-side code to detect and process query string parameters. A lot of other information can be read in the original article.
Assuming that the script or JSONP type is specified, the <script> tag is actually used instead of the XMLHttpRequest object when the data is received from the server. In this case, $.ajax () no longer returns a XMLHttpRequest object and does not pass event handlers, such as Beforesend.
Send data to Server
By default, AJAX requests use the Get method. Suppose you want to use the Post method to set the type parameters. This option also affects how content in the data option is sent to the server.
The data option can include a query string, such as Key1=value1&key2=value2, which can also be a mapping, for example {key1: ' value1 ', Key2: ' value2 '}. Assuming that the latter form is used, the data re-sender is converted into a query string. This process can also be avoided by setting the ProcessData option to false. Assuming that we want to send an XML object to the server, this processing might not be appropriate. And in this case, we should also change the value of the ContentType option and replace the default application/x-www-form-urlencoded with other appropriate MIME types.
Advanced options
The global option is used to block callback functions that respond to the registration, such as. Ajaxsend, or Ajaxerror, and similar methods. This is useful in some cases, such as sending requests that are very frequent and brief, and can be disabled in ajaxsend. For a number of other specific information about these methods, please refer to the following sections.
Assuming that the server requires HTTP authentication, the ability to use username and password can be set through the username and password options.
Ajax requests are time-limited, so error warnings are captured and processed to improve the user experience. Request time-out this parameter usually retains its default value, or it can be set globally by jquery.ajaxsetup, very rarely setting the timeout option again for a specific request.
By default, requests are always sent out, but it is possible for the browser to fetch data from his cache. To suppress the use of cached results, you can set the cache parameter to False. Suppose you want to infer that the data has not been changed since the last request and that you can set Ifmodified to true if you report an error.
Scriptcharset agrees to set a specific character set for the <script> tag request for script or JSONP similar data. This is especially useful when the script and page character sets are different.
The first letter of Ajax is the initial letter of the asynchronous, which means that all operations are parallel, and the order of completion is not related to each other. The async parameters of $.ajax () are always set to true, which indicates that other code can still run after the request has started. It is strongly not recommended to set this option to false, which means that all requests are no longer asynchronous, which also causes the browser to be locked out.
The $.ajax function returns the XMLHttpRequest object that he created. jquery typically only processes and creates this object internally, but users can also pass a XHR option to deliver a XHR object that they have created. The returned object is usually discarded, but still provides an underlying interface to observe and manipulate the request. For example, the. Abort () on the calling object can suspend the request before the request is complete.
Number of references
Url,[settings]Object
V1.5
URL: A URL string that is used to include sending requests.
settings: AJAX request settings. All options are optional.
V1.0
Settings: Options
accepts:Map
Default: Depends on the data type.
The content type sends the request header, telling the server what response will accept the return. Assuming that the accepts setting needs to be changed, it is recommended to do it once in the $.ajaxsetup () method.
Async:Boolean
(default: TRUE) by default, all requests are asynchronous requests. If you need to send a synchronization request, set this option to false. Note that the sync request will lock the browser, and the user's other actions must wait for the request to complete.
beforesend (XHR):Function
You can change the functions of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. The XMLHttpRequest object is the only number of parameters. This is an Ajax event. It is assumed that returning false can cancel this Ajax request.
function (XMLHttpRequest) { this;//options to be passed when calling this Ajax request}
Cache:Boolean
(Default: True,datatype for script and Jsonp Shime feel False) JQuery 1.2 new feature, set to False will not cache this page.
Complete (XHR, TS)Function
After the request is complete, the callback function (called after the request succeeds or fails). Parameters: XMLHttpRequest object and a string describing the type of successful request. Ajax events.
function (XMLHttpRequest, textstatus) { this;//options to be passed when calling this Ajax request}
Contents:Map
V1.5
An object paired with "{string: Regex}" to determine how jquery will parse the response, given its content type.
ContentType:String
(Default: "application/x-www-form-urlencoded") the content encoding type when sending information to the server. The default value is appropriate for most cases. Suppose you clearly pass a content-type to $.ajax () then he will certainly send it to the server (even if there is no data to send)
Context:Object
This object is used to set the context of the AJAX-related callback function. That is, let the this object in the callback function point (assuming that this parameter is not set, then this points to the options that were passed when the AJAX request was called). For example, a DOM element is specified as a context parameter, so that the success callback function is set to the DOM element. Just like this:
$.ajax ({url: "test.html", Context:document.body, Success:function () { $ (this). AddClass ("Done");});
ConvertersMap
V1.5
Default: {"* text": window. String, "text html": True, "text json": Jquery.parsejson, "text xml": Jquery.parsexml}
A data type object to the data type converter. The value of each converter is a function that returns the conversion value of the response
Crossdomain:Map
V1.5
Default: The same domain request is false
Cross-domain request is true if you want to force cross-domain requests (such as Jsonp form) to the same domain, set Crossdomain to True. This allows, for example, server end multiplicity to be directed to a domain
DataObject,:string
The data sent to the server. Convert yourself to the request string format. The GET request will be appended to the URL. View the ProcessData option description to prohibit this self-initiated conversion. Must be a key/value format. Assuming an array, JQuery will take its own initiative to have the same name for the different values. such as {foo:["bar1", "Bar2"]} is converted to "&foo=bar1&foo=bar2".
Datafilter:Function
The preprocessing function for the raw data returned by Ajax. Data and type two parameters are provided: Data is the original information returned by Ajax, and type is the datatype parameter supplied when calling Jquery.ajax. The value returned by the function will be further processed by jquery.
function (data, type) { //preprocessing of the original data returned by Ajax return data //return processing after}
DataType:String
Expected data type returned by the server. Assuming that it is not specified, JQuery intelligently infers itself based on the HTTP packet MIME information, as XML MIME types are recognized as XML. In 1.4, JSON generates a JavaScript object, and script runs it. The data returned by the server is then parsed by this value and passed to the callback function. Available values:
"XML": Returns an XML document that can be processed with jQuery.
HTML: Returns plain text HTML information, including script tags that run when the DOM is inserted.
"Script": Returns plain text JavaScript code. Do not actively cache the results themselves. Unless the "cache" parameter is set. ' Note: ' On a remote request (not in the same domain), all post requests will be converted to get requests. (because the script tag of the DOM will be used to load)
"JSON": Returns the JSON data.
"JSONP": Jsonp format. When calling a function using JSONP form, such as "myurl?callback=?" JQuery will voluntarily replace itself? is the correct function name to run the callback function.
"Text": Returns a plain text string
Error:Function
(Default: This function is called when the request fails on its own initiative (XML or HTML)). There are three parameters: the XMLHttpRequest object, the error message, and (optionally) the exception object that was caught. Assuming an error occurs, the error message (the second parameter) can be "timeout", "error", "Notmodified", and "ParserError" in addition to null. Ajax events.
function (XMLHttpRequest, textstatus, Errorthrown) { //usually Textstatus and Errorthrown //Only one will include information this ; Options that are passed when calling 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, which can be used to control different AJAX events.
headers:Map
V1.5
Default: {}
An additional "{Key: Value}" is sent with the map to the request. This setting is set before the Beforesend function is called; therefore, the value in the message header is set to overwrite whatever setting is within the scope of the Beforesend function.
ifmodified:Boolean
(default: false) to get new data only when the server data changes. Use the HTTP packet last-modified header information inference. In jquery 1.4, he also checks the server-specified ' ETag ' to determine that the data has not been altered.
isLocal:Map
V1.5.1
Default: Depends on the current location protocol
Agree that the current environment is recognized as "local" (such as a file system), even though jquery does not recognize it by default. The following agreement is now public feeling local: file, *-extension, and widget. It is recommended to do this once in the $.ajaxsetup () method, assuming the islocal settings need to be changed.
Jsonp:String
Overrides the name of the callback function in a JSONP request. This value is used instead of "callback=?" Such a GET or POST request in the URL parameter in the "Callback" section, for example {jsonp: ' onjsonpload '} will cause the "onjsonpload=?" passed to the server.
Jsonpcallback:String
Specifies a callback function name for the JSONP request. This value will be used instead of the random function name generated by jquery itself. This is primarily used to create a unique function name for jquery, which makes it easier to manage requests and provides a convenient way to provide callback functions and error handling. You can also specify this callback function name when you want the browser to cache a GET request.
MimeTypeString:
V1.5.1
A MIME type used to overwrite the MIME type of XHR.
Password:String
Password for responding to HTTP access authentication requests
ProcessData:Boolean
(default: TRUE) by default, the data is passed in as a single object (technically, only if it is not a string), and is processed into a query 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.
Scriptcharset:String
Only if the request is datatype as "JSONP" or "script", and type is "GET" is used to force the change CharSet. It is usually used only when local and remote content encodings are different.
StatusCode:Map
V1.5
Default: {}
A set of numeric HTTP code and function objects that call the corresponding code when responding. For example, assuming a response status of 404, the following alert will be triggered:
$.ajax ({ statusCode: {404:function () { alert (' Page not found '); }});
success (data, Textstatus, JQXHR):Function,array
The callback function after the request succeeds. Parameters: returned by the server and processed according to datatype parameters; A string describing the state of the narrative. There are also jqxhr (in jquery 1.4.x, XMLHttpRequest) objects. In jquery 1.5, a successful setting can accept an array of functions. Each function is called sequentially. Ajax events.
function (data, textstatus) { //data may be xmldoc, jsonobj, HTML, text, etc. .. This Options that are passed when calling this Ajax request}
Traditional:Boolean
If you want to serialize the data in a traditional way, set it to true. Please refer to the Jquery.param method below for the classification of tools.
Timeout:Number
Sets the request time-out (in milliseconds). This setting overrides the global settings.
typeString
(Default: "Get") The request mode ("POST" or "get"), which defaults to "get". Note: Other HTTP request methods, such as PUT and DELETE, can also be used, but only some browsers support it.
URL:String
(Default: Current page address) sends the requested address.
Username:String
Username for responding to HTTP access authentication requests
XHR:Function
You need to return a XMLHttpRequest object. The default is ActiveXObject under IE and in other cases it is xmlhttprequest. Used to override or provide an enhanced XMLHttpRequest object. This number was not available in jquery 1.3.
XhrfieldsMap
V1.5
A pair of "file names-file values" is set in the native Xhr object. For example, if required, you can use it to set Withcredentials to True cross-domain requests.