jquery Learning jquery Ajax Usage Detailed

Source: Internet
Author: User

[Introduction] jQuery Ajax in the Web application development is very common, it mainly includes ajax,get,post,load,getscript and so on several commonly used no refresh operation method, below I come to introduce to you students. Let's start with the simplest approach, when dealing with complex AJAX requests, JQuery uses Jque

JQuery Ajax in the Web application development is very common, it mainly includes the ajax,get,post,load,getscript and so on several commonly used no refresh operation method, let me give you the introduction of the students.

We'll start with the simplest approach, when dealing with complex AJAX requests, JQuery uses the Jquery.ajax () method for processing. There are some simple methods in jquery that encapsulate the Jquery.ajax () method so that we do not need to use the Jquery.ajax () method when dealing with some simple Ajax events, some of which have already appeared in previous articles, I believe you will soon be able to master it. Of course, the second half of this article will be very specific to the Jquery.ajax () method, because it is the most important part of this article.

The following 5 methods perform a short form of a generic AJAX request and should use Jquery.ajax () when dealing with complex AJAX requests.

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

Loads the remote HTML file code and inserts it into the DOM, by default, by using Get mode, which is automatically converted to post when passing parameters.

URL: The remote URL address to load
? data: Key/value data sent to the server
Callback: Callback function when loading success
The sample code is as follows:

The code is as follows Copy Code

No parameter, no callback function
$ ("#showload"). Load ("load.htm");
No callback function
$ ("#showload"). Load ("load.htm", {"para": "Para-value"});
$ ("#showload"). Load ("load.htm", {"para": "Para-value"},
function () {
Processing
})

The contents of the loaded file are displayed here load
2.jquery.get (URL, [data], [callback])
Get the data from the server side by using the Get method.

? The URL address of the sending request
? data to be sent to the server
? callback function when loading succeeds
The sample code is as follows:

The code is as follows Copy Code

$.get ("jqueryget.htm", {"id": this.id},
Function (req) {
Callback method when successful
$ ("#showget"). HTML (req);
});
})

Use the $.get () method to get a different logo by passing the ID. It is worth mentioning that at this point the request is obtained through the Get method, so when you get the parameter value, you use Request.QueryString to see the difference between the request Request.QueryString

Baidu logo Google logo

This will show Logo3.jQuery.post (URL, [data], [callback])
Use the Post method to make an asynchronous request. Compared with Jquery.get (), the difference is in the way of the request, so there is no special explanation, the use of the method is similar to Jquery.get ().

4.jquery.getscript (Url,[callback])

A JavaScript file is loaded and executed by a GET method request. This technology has been mentioned in the preceding article, is also a simple way to use Jquery.ajax, you can see the Ajax loading JS, so there is no special explanation.

5.jquery.getjson (Url,[data],[callback])
Gets the JSON-formatted data in the Get mode.

The sample 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 ");
       }
   });
});

Again, this is a shorthand method for the Jquery.ajax () method, similar to the following:

Parameter list:

Name of parameter Type Describe
wr. String (Default: Current page address) sends the requested address.
Type String (Default: "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.
Timeout Number Sets the request time-out (in milliseconds). This setting overrides the global settings.
Async Boolean (default: 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 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.
function (XMLHttpRequest) {  //The options for this AJAX request}

Cache Boolean (default: TRUE) JQuery 1.2 new feature, set to False will not load the request information from the browser cache. Complete The callback function (called when the request succeeds or fails) after the functions request completes. Parameters: XMLHttpRequest Object, Success information string.

function (XMLHttpRequest, textstatus) {  //The options for this AJAX request}

ContentType String (default: "application/x-www-form-urlencoded") the content encoding type when sending information to the server. The default values are suitable for most applications. Data Object,
String to send data 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 '. DataType String

Expected data type returned by the server. If not specified, JQuery automatically returns Responsexml or ResponseText based on the HTTP packet MIME information and is passed as a callback function parameter, with the available values:

"XML": Returns an XML document that can be processed with jQuery.

HTML: Returns plain text HTML information, including the script element.

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

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

Error Function (default: Auto-judge (XML or HTML)) calls this method when a request fails. This method has three parameters: the XMLHttpRequest object, the error message, and (possibly) the error object being captured.

function (XMLHttpRequest, textstatus, Errorthrown) {  //normally textstatus and Errorthown only one of the values   //The Options for this Ajax request} 

Global Boolean (default: TRUE) to trigger global AJAX events. Setting to FALSE will not trigger global AJAX events, such as Ajaxstart or Ajaxstop. Can be used to control different AJAX events ifmodified Boolean (default: false) to fetch new data only when the server data changes. Use the HTTP packet last-modified header information to determine. ProcessData Boolean (default: TRUE) by default, the sent data is converted to an object (technically not a 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. Success The callback function after the function request succeeds. This method has two parameters: the server returns data, returns the status

function (data, textstatus) {  //data could be xmldoc, jsonobj, HTML, text, etc ...  //The options for this AJAX request} 

Here are a few Ajax event parameters:beforesend ,success , complete, error. We can define these events to handle each of our AJAX requests well. Note that the this in these Ajax events is the option information that points to the Ajax request (refer to the picture of this for the Get () method).

The code is as follows Copy Code

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

Perhaps you have not used JSON data, my small station has mentioned the use of JSON several times, if you are not familiar with the JSON format, you can see the value of the jquery mobile ListBox, the use of JSON under jquery example

Get JSON data

Here will be a random JSON data so far we have summed up the Jquery.ajax five shorthand methods, then let us focus on the Jquery.ajax () method, in use, the author is also a frequent use of jquery.ajax (), because in most cases, We need to capture and process an AJAX request error.

6.jquery.ajax ()
Use the Jquery.ajax () method to get the data, below is a common way to write, and make the corresponding comments.

The code is as follows Copy Code

$.ajax ({
    URL:" http://www.hzhuti.com ",   //Requested URL address
     DataType: "JSON",  //Return format is JSON
    async:true,//request is asynchronous, default is async, this is Ajax important feature
    data: {"id": "Value"},   //Parameter value
    type: "GET",  // Request Method
    beforesend:function () {
       //processing before request
   ,
    success:function (req) {
        Handle
   } When the request succeeds,
    complete:function () {
        //Processing of request completion
   },
    error:function () {
        //Request error handling
   }
});

Using Jquery.ajax ()
The data is displayed here


$.ajax examples of my practical application

The code is as follows Copy Code

1.$.ajax asynchronous requests 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 asynchronous requests that serialize the contents of a table to a string
function Notips () {
var Formparam = $ ("#form1"). Serialize ();//serialization of table contents as strings
$.ajax ({
Type: ' Post ',
URL: ' Notice_notipsnotice ',
Data:formparam,
Cache:false,
DataType: ' JSON ',
Success:function (data) {
}
});
}


3.$.ajax asynchronous requests for stitching URLs
var Yz=$.ajax ({
Type: ' Post ',
URL: ' validatepwd2_checkpwd2?password2= ' +password2,
data:{},
Cache:false,
DataType: ' JSON ',
Success:function (data) {
if (data.msg = = "false")//the server returns false to change the value of ValidatePassword2 to Pwd2error, which is asynchronous and takes into account the return time
{
Textpassword2.html ("<font color= ' red ' > Business password is incorrect! </font> ");
$ ("#validatePassword2"). Val ("Pwd2error");
CheckPassword2 = false;
Return
}
},
Error:function () {}
});


4.$.ajax asynchronous request to splice data
$.ajax ({
URL: ' <%=request.getcontextpath ()%>/kc/kc_checkmernameunique.action ',
Type: ' Post ',
Data: ' Mername= ' +values,
Async:false,//default True Async
Error:function () {
Alert (' Error ');
},
Success:function (data) {
$ ("#" +divs). HTML (data);
}
});

The jquery Ajax use in this article is summarized here, of course, there are some methods are not fully summarized. such as Ajaxstart (), ajaxstop (), etc., in later use, I will summarize them.

jquery Learning jquery Ajax Usage Detailed

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.