JQueryAjax instance code ($. ajax, $. post, $. get) _ jquery

Source: Internet
Author: User
The following small series will bring you a jQueryAjax instance code ($. ajax, $. post, $. get ). I think it is quite good. Now I will share it with you and give you a reference $. post, $. get is a simple method. To process complicated logic, you still need to use jQuery. ajax ()

I. general format of $. ajax

$.ajax({   type: 'POST',   url: url ,  data: data ,  success: success ,  dataType: dataType});

2. $. ajax parameter description

Parameter description

Url Required. Specifies the URL to which the request is sent.
Data Optional. Ing or string value. Specifies the data sent to the server together with the request.
Success (data, textStatus, jqXHR) Optional. The callback function executed when the request is successful.

Optional. Specifies the expected server response data type.

Intelligent judgment (xml, json, script, or html) is performed by default ).

Iii. Notes for $. ajax:

1. There are three main methods of data: html splicing, json array, form serialized by serialize (); specified by dataType, no smart judgment is specified.

2. $. ajax only submits the form in text mode. If the asynchronous submission contains Upload is not passed. You need to use jquery. form. js's $. ajaxSubmit

Iv. Examples of my actual applications of $. ajax

// 1. $. ajax asynchronous request with json data var aj =$. ajax ({url: 'productmanager _ reverseupdat', // jump to action data: {selRollBack: selRollBack, selOperatorsCode: selOperatorsCode, PROVINCECODE: PROVINCECODE, pass2: pass2}, type: 'post', cache: false, dataType: 'json', success: function (data) {if (data. msg = "true") {// view ("modified successfully! "); Alert (" modified successfully! "); Window. location. reload () ;}else {view (data. msg) ;}, error: function () {// view (" exception! "); Alert (" exception! ") ;}}); // 2. $. ajax serialized asynchronous request function noTips () {var formParam = $ ("# form1") whose table content is a string "). serialize (); // serialize the table content as a string $. ajax ({type: 'post', url: 'notice _ noTipsNotice ', data: formParam, cache: false, dataType: 'json', success: function (data) {}});} // 3. $. asynchronous request var yz = $. ajax ({type: 'post', url: 'validatepwd2 _ checkPwd2? Password2 = '+ password2, data :{}, cache: false, dataType: 'json', success: function (data) {if (data. msg = "false") // when the server returns false, the value of validatePassword2 is changed to pwd2Error. This is asynchronous. You need to consider the return time {textPassword2.html ("the business password is incorrect! "); $ (" # ValidatePassword2 "). val ("pwd2Error"); checkPassword2 = false; return ;}}, error: function () {}}); // 4. $. asynchronous request for ajax splicing data $. ajax ({url: '<% = request. getContextPath () %>/kc/kc_checkMerNameUnique.action ', type: 'post', data: 'mername =' + values, async: false, // The default value is true asynchronous error: function () {alert ('error') ;}, success: function (data) {$ ("#" +ps).html (data );}});

Url: String-type parameter (the current page address by default.

Type: a parameter of the String type. The request method (post or get) is get by default. Note other http request methods, such as put and

Delete can also be used, but only some browsers support it.

Timeout: a parameter of the Number type is required. Set the request timeout time (in milliseconds ). This setting overwrites the global settings of the $. ajaxSetup () method.


Async: A Boolean parameter. The default value is true. All requests are asynchronous requests.

To send a synchronization request, set this option to false. Note: Synchronous requests will lock the browser and other user operations are required.

The request can be executed only after the request is complete.

Cache: A Boolean parameter. The default value is true. When dataType is script, the default value is false ).

Setting false does not load request information from the browser cache.

Data: data sent to the server using an Object or String parameter. If it is no longer a string, it is automatically converted to a string

. The get request will be appended to the url. To prevent this automatic conversion, you can view the processData option. The object must be in the key/value format.

Format. For example, {foo1: "bar1", foo2: "bar2"} is converted to & foo1 = bar1 & foo2 = bar2. If it is an array, JQuery will automatically be different

The value corresponds to the same name. For example, {foo: ["bar1", "bar2"]} is converted to & foo = bar1 & foo = bar2.

DataType: it must be a String type parameter. The data type returned by the server is expected. If this parameter is not specified, JQuery automatically uses the http package mime

ResponseXML or responseText is returned and passed as the callback function parameter.

The available types are as follows:

Xml: the XML document is returned and can be processed by JQuery.

Html: returns plain text HTML information. 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 that in the remote request

All post requests are converted to get requests.

Json: Return JSON data.

Jsonp: JSONP format. When a function is called in the form of SONP, such as myurl? Callback = ?, JQuery will automatically Replace the last

"?" For the correct function name to execute the callback function.

Text: returns a plain text string.

BeforeSend: a parameter of the Function type. Before sending a request, you can modify the Function of the XMLHttpRequest object, for example, adding a custom

HTTP header. In beforeSend, if false is returned, the ajax request can be canceled. The XMLHttpRequest object is the only parameter.


Function (XMLHttpRequest ){

This; // The options parameter passed when calling this ajax request


Complete: a parameter of the Function type. It is the callback Function called after the request is complete (all calls are called when the request is successful or fails ).

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

Function (XMLHttpRequest, textStatus ){

This; // The options parameter passed when calling this ajax request


Success: Required parameter of the Function type. The callback Function called after the request is successful has two parameters.

(1) data returned by the server and processed according to the dataType parameter.

(2) A string describing the status.

Function (data, textStatus ){

// Data may be xmlDoc, jsonObj, html, text, etc.

This; // The options parameter passed when calling this ajax request

Error: Required parameter of the Function type. The Function called when the request fails. This function has three parameters: XMLHttpRequest object and error

Optional ).

Ajax event functions are as follows:

Function (XMLHttpRequest, textStatus, errorThrown ){

// Generally, textStatus and errorThrown only contain one of the information.

This; // The options parameter passed when calling this ajax request


ContentType: String-type parameter. When the message is sent to the server, the content encoding type is default.

Is "application/x-www-form-urlencoded ". This default value is suitable for most applications.

DataFilter: a Function that requires Function-type parameters to pre-process the original data returned by Ajax.

Provides two parameters: data and type. Data is the original data returned by Ajax, and type is provided when jQuery. ajax is called.

DataType parameter. The value returned by the function will be further processed by jQuery.

Function (data, type ){

// Return the processed data

Return data;


Global: A Boolean parameter. The default value is true. Indicates whether to trigger a global ajax event. Setting this parameter to false does not trigger global events.

Ajax events, such as ajaxStart or ajaxStop, can be used to control various ajax events.

IfModified: A Boolean parameter. The default value is false. Obtain New data only when the server data changes.

The server data change judgment is based on the Last-Modified header information. The default value is false, indicating that the header information is ignored.

Jsonp: a parameter of the String type. In a jsonp request, rewrite the name of the callback function.

This value is used to replace "callback =? "Callback" in the URL parameter in this GET or POST request, for example

{Jsonp: 'onjsonpload'} causes "onJsonPLoad =? "To the server.

Username: a String-type parameter that is used to respond to an HTTP access authentication request.

Password: a String-type parameter used to respond to an HTTP access authentication request.

ProcessData: A Boolean parameter. The default value is true. By default, the sent data is converted to an object (technically

It is not a string) to use with the default content type "application/x-www-form-urlencoded ". If you want to send DOM

Set the tree information or other information that you do not want to convert to false.

ScriptCharset: a String-type parameter. Only when the dataType is "jsonp" or "script" and the type is GET

Is used to forcibly modify the character set (charset ). Generally, the local and remote content encoding is not used at the same time.

Case code:

$ (Function () {$ ('# send '). click (function () {$. ajax ({type: "GET", url: "test. json ", data: {username: $ (" # username "). val (), content: $ ("# content "). val ()}, dataType: "json", success: function (data) {$ ('# resText '). empty (); // clear all content in resText var html = ''; $. each (data, function (commentIndex, comment) {html + = ''+ comment ['username'] + ': + '';}); optional ('{restext'{.html (html );}});});});

By the way, the $. each () function:

$. The each () function is different from the each () method of the JQuery object. It is a global function that does not operate the JQuery object, but uses an array or object as 1st parameters, use a callback function as the 2nd parameter. The callback function has two parameters: 1st are the indexes of the object's members or arrays, and 2nd are the corresponding variables or content.

The above jQuery Ajax instance code ($. ajax, $. post, $. get) is all the content shared by Alibaba Cloud xiaobian. I hope you can give us a reference and support for your feet.

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.