How does Ajax work? Use case analysis of Ajax

Source: Internet
Author: User
Tags http authentication script tag string format

This article mainly describes the use of Ajax details, as well as the use of Ajax case resolution. Now let's see this article together.

$.ajax () method use case

Need to introduce a jquery file, this case uses the Jquery-2.0.0.js

1, ajax.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

2, Userservlet.java

@WebServlet ("/ajax.do") public class Ajaxservlet extends HttpServlet {protected void DoPost (HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {//Request Chinese garbled handling request.setcharacterencoding ("UTF-8") ;//Response Chinese garbled processing response.setheader ("Content-type", "text/html;charset=utf-8");//Receive data string name = Request.getparameter ( "Name"); SYSTEM.OUT.PRINTLN (name);//test exception, Ajax will execute error//throw new IOException (); PrintWriter out = Response.getwriter ();//Response Information Out.write ("Success ..."); Out.flush (); Out.close ();}}

The $.ajax () method is described in detail below (from W3school)

JQuery Ajax-ajax () method

Instance

To load a piece of text via AJAX:

JQuery Code:

$ (document). Ready (function () {  $ ("#b01"). Click (function () {  htmlobj=$.ajax ({url: "/jquery/test1.txt", Async:false});  $ ("#myp"). HTML (htmlobj.responsetext);  });

HTML Code:

<p id= "MYP" >

Definition and usage

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

This method is the jQuery underlying AJAX implementation. 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: All options can be set globally through the $.ajaxsetup () function.

Grammar

Jquery.ajax ([Settings])
Parameters Description
Settings

Optional. The collection of key-value pairs used to configure the Ajax request.

You can set default values for any option through $.ajaxsetup ().

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

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

  • Cache

  • Type: Boolean

    Default value: False when True,datatype is script and Jsonp. Set to False to not cache this page.

    New features of JQuery 1.2.

  • Complete (XHR, TS)

  • Type: Function

    The callback function after the request is completed (called after the request succeeds or fails).

    Parameters: XMLHttpRequest object and a string describing the request type.

    This is an Ajax event.

  • ContentType

  • Type: String

    Default value: "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 it will certainly be sent to the server (even if there is no data to send).

  • Context

  • Type: 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");}      );
  • Data

  • Type: 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"]} converted to ' &foo=bar1&foo=bar2 '.

  • Datafilter

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

  • DataType

  • Type: 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 remote requests (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

  • Type: Function

    Default value: Auto-Judgment (XML or HTML). This function is called when a request 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.

    This is an Ajax event.

  • Global

  • Type: Boolean

    Whether to trigger global AJAX events. Default value: True. Setting to FALSE will not trigger global AJAX events, such as Ajaxstart or ajaxstop, which can be used to control different AJAX events.

  • Ifmodified

  • Type: Boolean

    Get new data only when the server data changes. Default value: False. Use the HTTP packet last-modified header information to determine. In JQuery 1.4, it also checks the server-specified ' ETag ' to determine that the data has not been modified.

  • Jsonp

  • Type: String

    Overrides the name of the callback function in a JSONP request. This value is used instead of the "callback" part of the URL parameter in the "callback=?" Get or POST request, such as {jsonp: ' onjsonpload '} will cause the "onjsonpload=?" to be passed to the server.

  • Jsonpcallback

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

  • Password

  • Type: String

    Password in response to HTTP access authentication request

  • ProcessData

  • Type: Boolean

    Default value: 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

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

  • Success

  • Type: Function

    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.

    This is an Ajax event.

  • Traditional

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

  • Type: Number

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

  • Type

  • Type: String

    Default value: "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

  • Type: String

    Default value: The current page address. The address where the request was sent.

  • Username

  • Type: String

    The user name used to respond to HTTP access authentication requests.

  • Xhr

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

callback function

If you are working with $.ajax () data, you need to use a callback function: Beforesend, error, Datafilter, success, complete.

Beforesend

Called before the request is sent, and a xmlhttprequest is passed in as a parameter.

Error

Called when there is an error in the request. Incoming XMLHttpRequest object, a string describing the type of error, and an exception object (if any)

Datafilter

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

This function is called when the request is complete, 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 ensure 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 you specify the script type, the server-side build JavaScript is executed before the script is returned 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 a result. To achieve this, it first tries 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 (). (Want to see more on the Topic.alibabacloud.comAJAX Development Manual section of the study)

Note: JSONP is an extension in JSON format. It requires some server-side code to detect and process query string parameters.

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.

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 the browser may be able to fetch data from its 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 it 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.

This is the end of this article (want to see more on the Topic.alibabacloud.comAJAX User manual section of the study), there are questions can be in the message below the question.

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.