JQuery Ajax usage and jqueryajax usage

Source: Internet
Author: User
Tags getscript

JQuery Ajax usage and jqueryajax usage
JQuery Ajax is often used in web application development. It mainly includes ajax, get, post, load, getscript, and so on, next I will introduce you to you.

Let's start with the simplest method. jQuery uses the jQuery. ajax () method to process complicated ajax requests. There are some simple methods in jQuery. the ajax () method is encapsulated so that jQuery is not required when processing some simple Ajax events. ajax () methods, some of which have already appeared in previous articles. I believe you will be able to master them soon. Of course, the second half of this article will explain jQuery. ajax () very specifically, because it is the top priority of this article.

 

The following five methods are used to execute the short form of a general Ajax request. jQuery. Ajax () should be used to process complicated ajax requests ().

1. load (url, [data], [callback])

Load the remote HTML file code and insert it into the DOM. The GET method is used by default, and the parameter is automatically converted to the POST method when passing parameters.

Upload url: the remote url to be loaded
Transmit data: key/value data sent to the server
Callback: the callback function when the load is successful.
The sample code is as follows:

The Code is as follows: Copy code

// No parameter or callback function
$ ("# Showload"). load ("load.htm ");
// No callback function
$ ("# Showload"). load ("load.htm", {"para": "para-value "});
$ ("# Showload"). load ("load.htm", {"para": "para-value "},
Function (){
// Process
})

Load
2. jQuery. get (url, [data], [callback])
Use get to obtain data from the server.

The URL of the request sent by the producer
The data that the producer wants to send to the server.
Callback function when the listener is loaded successfully
The sample code is as follows:

The Code is as follows: Copy code

$. Get ("jqueryget.htm", {"id": this. id },
Function (req ){
// Callback Method for success
$ ("# Showget" pai.html (req );
});
})

Use the $. get () method to get different logos by passing IDs. It is worth mentioning that the Request is obtained through the get method. Therefore, you must use Request. QueryString to obtain the parameter value. You can see the difference between Request. QueryString and Request. QueryString.

Baidu logo Google logo

Logo3.jQuery. post (url, [data], [callback]) will be displayed here
Use the POST method for asynchronous requests. Compared with jQuery. get (), the difference lies in the request method. Therefore, we do not make a special description here. The method of use is similar to jQuery. get.

4. jQuery. getScript (url, [callback])

Load and execute a JavaScript file using GET requests. This technology has been mentioned in the previous article. It is also a simple method of using jQuery. ajax. You can see how ajax loads js, so it is not particularly explained here.

5. jQuery. getJSON (url, [data], [callback])
Get data in json format.

The sample code is as follows:

The Code is as follows: Copy code

$. GetJSON ("http://api.flickr.com/services/feeds/photos_public.gne? Tags = cat & tagmode = any & format = json & jsoncallback =? ", Function (req ){
$. Each (req. items, function (I, item ){
If (I = vnum ){
$ (" "). appendTo ("# showjson ");
}
});
});

Similarly, this is also a short method of jQuery. ajax () method, similar to the following method:

Parameter List:

Parameter Name Type Description
Url String (Default: Current page address) the address of the request sent.
Type String (Default: "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.
Timeout Number Set the request timeout (in milliseconds ). This setting overwrites the global setting.
Async Boolean (Default: 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 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.
function (XMLHttpRequest) {  this; // the options for this ajax request}
Cache Boolean (Default: true) New jQuery 1.2 function. setting this parameter to false will not load request information from the browser cache.
Complete Function Callback Function after the request is complete (called when the request is successful or fails ). Parameter: XMLHttpRequest object, success information string.
function (XMLHttpRequest, textStatus) {  this; // the options for this ajax request}
ContentType String (Default: "application/x-www-form-urlencoded") Content Encoding type when sending information to the server. The default value is applicable to most applications.
Data Object,
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 '.
DataType String

Expected data type returned by the server. If this parameter is not specified, jQuery will automatically return responseXML or responseText Based on the MIME information of the HTTP package and pass it as a callback function parameter. Available values:

"Xml": returns an XML document, which can be processed by jQuery.

"Html": returns plain text HTML information, including script elements.

"Script": returns plain text JavaScript code. Results are not automatically cached.

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

 

 

 

 

 

Error Function (Default: automatically determines (xml or html) This method is called when a request fails. This method has three parameters: XMLHttpRequest object, error message, and (possibly) captured error object.
Function (XMLHttpRequest, textStatus, errorThrown) {// Generally, only one of textStatus and errorThown has the value this; // the options for this ajax request}
Global Boolean (Default: true) Whether to trigger a global AJAX event. Setting false does not trigger global AJAX events, such as ajaxStart or ajaxStop. Can be used to control different Ajax events
IfModified Boolean (Default: false) obtain new data only when the server data changes. Use the Last-Modified header information of the HTTP packet to determine.
ProcessData Boolean (Default: true) by default, data sent is converted to an object (technically 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.
Success Function Callback Function after successful request. This method has two parameters: the server returns data and returns the status.
function (data, textStatus) {  // data could be xmlDoc, jsonObj, html, text, etc...  this; // the options for this ajax request}

Here are several Ajax event parameters:BeforeSend,Success,Complete, error.We can define these events to process every Ajax request. Note that this in these Ajax events points to the option Information of the Ajax request (see the image of this in the get () method ).

The Code is as follows: Copy code

$. Ajax ({
Url: url,
DataType: 'json ',
Data: data,
Success: callback
});

You may not have used json data. I have mentioned json usage several times in my website. If you are not familiar with json format, let's take a look at the value of jquery's mobile listbox and the example of json in jQuery.

Obtain json data

Here we will randomly display a piece of json data. So far we have summarized jQuery. let's take a look at jQuery. the ajax () method is often used by the author. ajax (). In most cases, we need to capture and process errors in ajax requests.

6. jQuery. ajax ()
Use the jQuery. ajax () method to obtain data. Below is a common method and corresponding annotations are provided.

The Code is as follows: Copy code

$. Ajax ({
Url: "http://www.hzhuti.com", // The requested url
DataType: "json", // The returned format is json.
Async: true, // whether the request is asynchronous. The default value is asynchronous, which is also an important feature of ajax.
Data: {"id": "value"}, // parameter value
Type: "GET", // Request Method
BeforeSend: function (){
// Pre-Request Processing
},
Success: function (req ){
// Process the request successfully
},
Complete: function (){
// Process the request
},
Error: function (){
// Handle request errors
}
});

Use jQuery. ajax ()
Data will be displayed here


$. Ajax my actual application example

The Code is as follows: Copy code

// 1. $. ajax asynchronous request with json data
Var aj = $. ajax ({
Url: 'productmanager _ reverseupdate', // 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 serialize asynchronous requests whose table content is a string
Function noTips (){
Var formParam = $ ("# form1"). 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 for url Splicing
Var yz = $. ajax ({
Type: 'post ',
Url: 'validatepwd2 _ checkPwd2? Password2 = '+ password2,
Data :{},
Cache: false,
DataType: 'json ',
Success: function (data ){
If (data. msg = "false") // if the server returns false, change the value of validatePassword2 to pwd2Error. This is asynchronous and the return time must be considered.
{
TextPassword2.html ("<font color = 'red'> incorrect business password! </Font> ");
$ ("# ValidatePassword2"). val ("pwd2Error ");
CheckPassword2 = false;
Return;
}
},
Error: function (){}
});


// 4. $. ajax Concatenates the asynchronous request of 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 ){
$ ("#" Nvidivs#.html (data );
}
});

The usage of jQuery ajax in this article is summarized here. Of course, there are still some methods that cannot be fully summarized. For example, ajaxStart () and ajaxStop (). I will summarize them later.


Unless otherwise stated, all PHP100 news reports are original or contributed. For reposted reports, please indicate the author and original article links.
Address: http://www.php100.com/html/program/jquery/2013/0905/6004.html

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.