JQuery AJAX $. ajax () method, jquery. ajax

Source: Internet
Author: User

JQuery AJAX $. ajax () method, jquery. ajax
AJAX = Asynchronous JavaScript and XML.
AJAX is a technology for creating fast dynamic web pages.
AJAX allows asynchronous updates on webpages by exchanging a small amount of data with the server in the background. This means that it is possible to update part of the webpage without reloading the whole page.
The JQuery script Library provides many AJAX submission methods, but the main methods are $. get (), $. post (), and $. ajax (). Where $. ajax () is the underlying implementation of the first two methods. It provides more attributes and parameter settings than the first two. If advanced settings are required, we recommend that you use $. ajax () method.
[For more information, see http://blog.csdn.net/mahoking]


Learn the $. get () method
Learn the $. post () method
Learn the $. ajax () method


$. Ajax () method
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.
Syntax:
JQuery. ajax ([settings])
Note:
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 ");
}});
Data
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 '.
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.
Demo case:
1. Create a Web project JQueryAjax.
2. Create js/jquery file directory under WebRoot and add jquery-2.1.1.js

3. Create a Servlet (AjaxServlet ). As follows:

public class AjaxServlet extends HttpServlet {public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String userName = request.getParameter("userName");String age = request.getParameter("age");PrintWriter out = response.getWriter();out.print("POST:userName="+userName+",age="+age);out.flush();}public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String userName = request.getParameter("userName");String age = request.getParameter("age");PrintWriter out = response.getWriter();out.print("GET:userName="+userName+",age="+age);out.flush();}}

4. Create jquery_ajax_method_ajax.jsp.

<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html> 

5. Deploy the project to Tomcat and test it.

[For more information, see http://blog.csdn.net/mahoking]

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.