The AJAX study of jquery

Source: Internet
Author: User
Tags http authentication script tag

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 with a server and updating parts of a Web page without reloading the entire page.

2, what is AJAX? AJAX = asynchronous JavaScript and XML.
AJAX is a technique for creating fast, Dynamic Web pages.
AJAX enables Web pages to be updated asynchronously by exchanging small amounts of data in the background with the server. This means that you can update a part of a webpage without reloading the entire page.
Traditional Web pages (without AJAX) if you need to update the content, you must reload the entire page surface.

There are many 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 reloading the entire page.

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 a request to the 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
Describe
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 Describe
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 perform 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
Describe
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 tasks that are performed 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 HTTP requests.

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 more flexibility.

In the simplest case, $.ajax () can be used directly without any parameters.

note that all options can be set globally through the $.ajaxsetup () function.

callback function

If you are working with $.ajax () data, 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, a string describing the type of error, and an exception object (if any)
    • Datafilter is called after the request succeeds. The returned data is passed in as well as the value of the "DataType" parameter. and the new data (possibly processed) must be returned to the success callback function.
    • Success called after the request. The data after the incoming return, and the string containing the success code.
    • Complete the function is called after the request is completed, regardless of success or failure. The incoming XMLHttpRequest object, and a string containing the success or error code.

Data type

The $.ajax () function relies on the information provided by the server to process the returned data. If the server reports that the returned data is XML, then the returned result can be traversed using either a normal XML method or a jquery selector. If other types, such as HTML, are seen, the data is treated in textual form.

The datatype option also allows you to specify different methods of data processing. In addition to simple XML, you can specify HTML, JSON, JSONP, script, or text.

Where 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.

If specified as an HTML type, any inline JavaScript will be executed before the HTML is returned as a string. Similarly, if the script type is specified, the server-side generation of JavaScript is executed before it is returned as a textual data.

If 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 is not supported, a function is used to build it. JSON data is a structured data that can be easily parsed by JavaScript. If 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 this type, a query string parameter callback= is created? , this parameter 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. If you want to specify the parameter name of the callback function instead of the default callback, you can set the JSONP parameter of the $.ajax ().

Note that Jsonp is an extension in JSON format. He asked for some server-side code to detect and process query string parameters. For more information, refer to the original article.

If a script or JSONP type is specified, then when the data is received from the server, the <script> tag is actually used instead of the XMLHttpRequest object. In this case, $.ajax () no longer returns a XMLHttpRequest object, and it does not pass an event handler, such as Beforesend.

Sending data to the server

By default, AJAX requests use the Get method. If you want to use the Post method, you can set the type parameter value. This option also affects how content in the data option is sent to the server.

The data option can contain either a query string, such as key1=value1&key2=value2, or a mapping, such as {key1: ' value1 ', Key2: ' value2 '}. If 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. This processing may not be appropriate if we want to send an XML object to the server. 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 registrations, such as. Ajaxsend, or Ajaxerror, and similar methods. This can be useful in some cases, such as when sending requests that are very frequent and short, so that this is disabled in Ajaxsend. For more information on these methods, see below.

If the server requires HTTP authentication, the user name and password can be set using the username and password options.

Ajax requests are limited, so error warnings are captured and processed, which can be used to improve the user experience. Request Timeout This parameter usually retains its default value, or it is set globally by Jquery.ajaxsetup, and the timeout option is rarely reset 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. You can set Ifmodified to True if you want to determine that the data has not been changed since the last request and the error is reported.

Scriptcharset allows you to set a specific character set for a <script> tag request for script or JSONP similar data. This is especially useful when scripting and page character sets are not the same.

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 parameter of $.ajax () is always set to true, which indicates that other code will still be able to execute 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 completed.

Parameters Url,[settings]Object V1.5

URL: A URL string to contain the sending request.

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 kind of response will accept the return. If the accepts setting needs to be modified, 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 before it can be executed.

beforesend (XHR):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. This is an Ajax event. If you return False, you can cancel this Ajax request.

function (XMLHttpRequest) {    this;//The options parameter passed when calling this Ajax request}

Cache:Boolean

(Default: True,datatype is script and Jsonp when the default is False) JQuery 1.2 new feature, set to False will not cache this page.

Complete (XHR, TS)Function

The callback function after the request is completed (called after the request succeeds or fails). Parameters: The XMLHttpRequest object and a string that describes the successful request type. Ajax events.

function (XMLHttpRequest, textstatus) {    this;//The options parameter passed when calling this Ajax request}

Contents:Map V1.5

An object paired with "{string: Regular expression}" 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. If you explicitly 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 (if this parameter is not set, then this points to the options parameter that is passed when the AJAX request is called). For example, you specify a DOM element as the context parameter, so that you set the success callback function to be 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 true if you want to force cross-domain requests (such as Jsonp form) to the same domain, set Crossdomain to True. This enables, for example, server end multiplicity to be directed to another domain

DataObject,:string

Data sent to the server. is automatically converted to the request string format. The GET request will be appended to the URL. View the ProcessData option description to disallow this automatic conversion. Must be a key/value format. If an array, JQuery automatically corresponds to 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 data 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. If not specified, JQuery is automatically judged intelligently based on the HTTP packet mime information, such as the XML MIME type being recognized as XML. In 1.4, JSON generates a JavaScript object, and script executes it. The data returned by the server is then parsed against 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, and the included script tag is executed when the DOM is inserted.

"Script": Returns plain text JavaScript code. Results are not automatically cached. Unless the "cache" parameter is set. "Note:" On a remote request (not in the same domain), all post requests are 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 is automatically replaced? is the correct function name to execute the callback function.

"Text": Returns a plain text string

Error:Function

(Default: This function is called when a request for automatic judgment (XML or HTML) fails.) There are three parameters: the XMLHttpRequest object, the error message, and (optionally) the exception object that is caught. If an error occurs, the error message (the second argument) may also be "timeout", "error", "Notmodified", and "ParserError", in addition to being null. Ajax events.

function (XMLHttpRequest, textstatus, Errorthrown) {    //usually Textstatus and Errorthrown    //Only one will contain information this    ;//Tune Options parameters passed with 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 can be overridden in any setting that overrides 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 to determine. In jquery 1.4, he also checks the server-specified ' ETag ' to determine that the data has not been modified.

isLocal:Map V1.5.1

Default: Depends on the current location protocol

Allows the current environment to be considered "local", such as a file system, even if jquery does not recognize it by default. The following protocols are currently recognized as Local: file, *-extension, and widget. If the islocal setting needs to be modified, it is recommended to do so once in the $.ajaxsetup () method.

Jsonp:String

Overrides the name of the callback function in a JSONP request. This value is used instead of "callback=?" The "callback" part of the URL parameter in this get or POST request, such as {jsonp: ' onjsonpload ', causes 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 automatically. 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 in response to HTTP access authentication request

ProcessData:Boolean

(default: TRUE) by default, the data option is passed in, and if it is an object (technically, as long as it is not a string), it will be 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 modification of CharSet. Typically 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 appropriate code when responding. For example, if the response status is 404, the following alerts 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: The data returned by the server and processed according to the datatype parameter; A string describing the state. 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 The options parameter 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 under the Tools category.

Timeout:Number

Sets the request time-out (in milliseconds). This setting overrides the global settings.

typeString

(Default: "Get") The Request method ("POST" or "get"), the default is "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

User name used in response to HTTP access authentication requests

XHR:Function

You need to return a XMLHttpRequest object. The default is ActiveXObject under IE and in other cases is xmlhttprequest. Used to override or provide an enhanced XMLHttpRequest object. This parameter is not available until jquery 1.3.

XhrfieldsMap V1.5

A pair of "filename-file Values" is set in the native Xhr object. For example, if necessary, you can use it to set Withcredentials to True cross-domain requests.



The AJAX study of jquery

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.