Jquery Ajax () method summary

Source: Internet
Author: User
Tags http authentication
Definition and usage

The Ajax () method loads remote data through an HTTP request.

This method is implemented by jquery underlying Ajax. For easy-to-use high-level implementation, see $. Get, $. Post, and so on. $. Ajax () returns the created XMLHTTPRequest object. In most cases, you do not need to directly operate on this function unless you need to operate on uncommon options for more flexibility.

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

Note:All options can be set globally using the $. ajaxsetup () function.

Syntax
 
Jquery. Ajax ([Settings])
Parameters Description
Settings

Optional. Set of key-value pairs used to configure Ajax requests.

You can use $. ajaxsetup () to set the default values of any options.

Parameters
Options

Type: Object

Optional. Ajax request settings. All options are optional.

Async

Type: Boolean

Default Value: 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 (xhr)

Type: 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.

This is an Ajax event. If false is returned, the Ajax request can be canceled.

Cache

Type: Boolean

Default Value: True. If script ype is set to script or jsonp, the default value is false. If this parameter is set to false, the page is not cached.

New Functions of jquery 1.2.

Complete (xhr, TS)

Type: Function

Callback Function after the request is complete (called after the request is successful or fails ).

Parameter: XMLHTTPRequest object and a string that describes the request type.

This is an Ajax event.

Contenttype

Type: String

Default Value: "application/X-WWW-form-urlencoded ". Content Encoding type when sending information to the server.

The default value is applicable in most cases. If you explicitly pass a Content-Type to $. Ajax (), it will certainly be sent to the server (even if there is no data to be sent ).

Context

Type: Object

This object is used to set the context of Ajax-related callback functions. That is to say, let this in the callback function point to this object (if this parameter is not set, this points to the options parameter passed when this Ajax request is called ). For example, if you specify a DOM element as the context parameter, the context of the success callback function is set to this Dom element.

Like this:

$. Ajax ({URL: "test.html", context: Document. Body, success: function () {$ (this). addclass ("done ");}});
Dataobject

Type: 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 '.

Example:
 
Here, the parameters following data can be written in two forms: one is to write common URL parameters, and the other is to write them in a JSON array,
The data section in the preceding example can also be written as follows: Data: {name: "John", Location: "Boston "}. What are the differences between the two statements?
Today, I found a slight difference in the usage of the two in development.First, we use the URL to pass parameters. If the parameter contains the "&" symbol, the parameters may not be received or are incomplete., Such as "data:" name = John & location = Boston ",",
If the name value is "John & Smith", this may cause a problem. We can escape it using the encodeuricomponent () method in Js,
However, if you use data: {name: "John", Location: "Boston"}, you do not need to escape it. If you escape it, you will receive the escaped string.
Datafilter

Type: Function

A preprocessing function for the original data returned by Ajax. Two parameters are provided: data is the original data returned by Ajax, and type is the datatype parameter provided when jquery. Ajax is called. The value returned by the function will be further processed by jquery.

Datatype

type: String

expected data type returned by the server. If this parameter is not specified, jquery automatically determines Based on the mime information of the http package. For example, the xml mime type is recognized as XML. In 1.4, JSON will generate a JavaScript Object, and script will execute this script. The data returned by the server is parsed based on this value and passed to the callback function. Available value:

  • "XML": returns an XML document, which can be processed by jquery.
  • "html": returns plain text HTML information. The 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: During remote requests (not in the same domain), all post requests are converted to GET requests. (Because the script tag of Dom will be used for loading)
  • "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.
  • "text": returns a plain text string.
Error

Type: Function

Default Value: Automatic judgment (XML or HTML ). This function is called when the request fails.

There are three parameters: XMLHTTPRequest object, error message, and (optional) caught exception object.

If an error occurs, in addition to null, the error message (the second parameter) may also be "timeout", "error", "notmodified", and "parsererror ".

This is an Ajax event.

Global

Type: Boolean

Whether to trigger a global Ajax event. Default Value: True. Setting false does not trigger global Ajax events. For example, ajaxstart or ajaxstop can be used to control different Ajax events.

Ifmodified

Type: Boolean

Obtain New data only when the server data changes. Default Value: false. Use the last-modified header information of the HTTP packet to determine. In jquery 1.4, it also checks the 'etag' specified by the server to confirm that the data has not been modified.

Jsonp

Type: String

Rewrite the name of the callback function in a jsonp request. This value is used to replace "Callback =? "The" Callback "section of the URL parameter in this get or POST request, for example, {jsonp: 'onjsonpload'} causes" onjsonpload =? "To the server.

Jsonpcallback

Type: String

Specify a callback function name for the jsonp request. This value is used to replace the random function name automatically generated by jquery. This function is mainly used to make jquery generate a unique function name, which makes it easier to manage requests and conveniently provide callback functions and error handling. You can also specify the callback function name when you want the browser to cache the GET request.

Password

Type: String

Password used to respond to HTTP access authentication requests

Processdata

Type: Boolean

Default Value: True. By default, data transmitted through the data option is converted into a query string if it is an object (technically, as long as it is 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.

Scriptcharset

Type: String

Only when the ype is "jsonp" or "script" and the type is "get" Can the charset be forcibly modified. It is usually used only when the local and remote content encoding is different.

Success

Type: Function

The callback function after the request is successful.

Parameter: the data that is returned by the server and processed according to the datatype parameter; a string that describes the status.

This is an Ajax event.

Traditional

Type: Boolean

If you want to serialize data in a traditional way, set it to true. See the jquery. Param method below the tool category.

Timeout

Type: Number

Set the request timeout (in milliseconds ). This setting overwrites the global setting.

Type

Type: String

Default Value: "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.

URL

Type: String

Default Value: the current page address. The address where the request is sent.

Username

Type: String

The username used to respond to the HTTP access authentication request.

Xhr

Type: Function

You need to return an XMLHTTPRequest object. Activexobject in IE and XMLHttpRequest in other cases by default. Used to override or provide an enhanced XMLHTTPRequest object. This parameter is unavailable before jquery 1.3.

 

Callback Function

If you want to process the data obtained by $. Ajax (), you need to use the callback functions: beforesend, error, datafilter, success, and complete.

Beforesend

Call before sending the request, and input an XMLHttpRequest as the parameter.

Error

This API is called when a request error occurs. Input the XMLHTTPRequest object to describe the string of the Error Type and an exception object (if any)

Datafilter

It is called after the request is successful. Input the returned data and the value of the "datatype" parameter. New data (which may have been processed) must be returned and passed to the success callback function.

Success

Called after a request. Input the returned data and a string containing the successful code.

Complete

Call this function after the request is complete, whether it is successful or failed. Input the XMLHTTPRequest object and a string containing successful or error code.

Data Type

The $. Ajax () function depends on the information provided by the server to process the returned data. If the server reports that the returned data is XML, the returned results can be traversed using the common XML method or jquery selector. If you see other types such as HTML, the data is treated as text.

You can use the datatype option 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 responsetext or responsehtml attribute of XMLHttpRequest to the success callback function.

Note:Make sure that the MIME type of the webpage Server Report matches the datatype we selected. For example, if XML is used, the server must declare text/XML or application/XML to obtain consistent results.

If it is specified as HTML, any embedded Javascript will be executed before HTML is returned as a string. Similarly, if the script type is specified, the server will first generate JavaScript and then return the script as a text data.

If the JSON type is specified, the obtained data is parsed as a JavaScript Object and the constructed object is returned as the result. To achieve this, it first tries to use JSON. parse (). If the browser does not support this function, you can use a function to build it.

JSON data is a structured data that can be easily parsed using JavaScript. If the obtained data file is stored on a remote server (the domain name is different, that is, cross-Origin data retrieval), The jsonp type is required. If this type is used, a query string parameter callback =? will be created? This parameter is added after the request URL. The server should add the callback function name before the JSON data to complete a valid jsonp request. If you want to specify the callback function parameter name to replace the default callback, you can set the jsonp parameter of $. Ajax.

Note:Jsonp is an extension of JSON format. It requires some server code to detect and process query string parameters.

If the script or jsonp type is specified, the <SCRIPT> label instead of the XMLHTTPRequest object is used to receive data from the server. In this case, $. Ajax () no longer returns an XMLHTTPRequest object and does not pass event processing functions, such as beforesend.

Send data to 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 the content in the Data option is sent to the server.

The data option can contain a query string, such as key1 = value1 & key2 = value2, or a ing, such as {key1: 'value1 ', key2: 'value2 '}. If the latter form is used, the data transmitter is then 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. 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 registration, such as. ajaxsend or ajaxerror, and similar methods. This is useful in some cases. For example, if a request is sent frequently and briefly, you can disable it in ajaxsend.

If the server requires HTTP authentication, you can use the username and password options to set them.

Ajax requests are time-limited. Therefore, error warnings can be captured and processed to improve user experience. The default value of the Request timeout parameter is usually retained. Otherwise, the parameter is globally set through jquery. ajaxsetup, And the timeout option is rarely reset for specific requests.

By default, requests are always sent, but the browser may retrieve data from its cache. To disable cache results, set the cache parameter to false. If you want to report an error when the data has not been changed since the last request, you can set ifmodified to true.

Scriptcharset allows you to set a specific character set for requests with the <SCRIPT> tag for script or jsonp-similar data. This is especially useful when scripts and page character sets are different.

The first letter of AJAX is the start Letter of asynchronous, which means that all operations are parallel and the order of completion is irrelevant. The async parameter of $. Ajax () is always set to true, which indicates that other code can still be executed after the request starts. It is strongly not recommended to set this option to false, which means that all requests are no longer asynchronous, And the browser will be locked.

$. The Ajax function returns the XMLHTTPRequest object it created. Generally, jquery only processes and creates this object internally, but you can also use the xhr option to pass an xhr object created by yourself. The returned object is usually discarded, but an underlying interface is provided to observe and manipulate the request. For example, the. Abort () on the call object can suspend the request before the request is completed.

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.