About jquery Ajax usage details _jquery

Source: Internet
Author: User
Tags error handling getscript string format browser cache

Definitions and usage

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

The approach is the jQuery-bottom AJAX implementation. Simple and easy-to-use high-level implementation see $.get, $.post, etc. $.ajax () returns the XMLHttpRequest object that it created. Most of the time you don't have 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.

JQuery Ajax in the Web application development is very common, it mainly includes ajax,get,post,load,getscript and so on these several commonly used no refresh operation method, below I will introduce to you the classmate.

Let's start with the simplest way of looking at a complex AJAX request, which 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 chapter 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 general 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, using the Get method by default, which is automatically converted to post when the parameter is passed.

◦url: Remote URL address to load
◦data: Key/value data sent to the server
◦callback: callback function when load succeeds

The sample code is as follows:

No parameters, 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
 })

This will show the contents of the loaded file load

2.jquery.get (URL, [data], [callback])

Use get to fetch data from the server side.

◦ Send the requested URL address
◦ data to be sent to the server
callback function when ◦ Load succeeds

The sample code is as follows:

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

Use the $.get () method to obtain a different logo by passing the ID. It is worth mentioning, at this time is the Get method to obtain the request, so when you get the parameter value to use Request.QueryString, you can see the request Request.QueryString Difference

Baidu logo Google logos

This will show Logo3.jQuery.post (URL, [data], [callback])
Use the Post method to make an asynchronous request. In contrast to Jquery.get (), the difference is in the way the request is made, so there is no special description here, and the use method is similar to Jquery.get ().

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

Load and execute a JavaScript file through a Get method request. This technology has been mentioned in the preceding article, is also a simple use of jquery.ajax, you can see Ajax loading JS, so here do not make a special note.

5.jquery.getjson (Url,[data],[callback])

Gets the data in JSON format.

The sample code is as follows:

$.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) {
   $ ("  
 

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

Parameter list:

Name of parameter Type Describe
Url String (Default: Current page address) sends the requested address.
Type String (Default: "Get") Request method ("POST" or "get"), default to "get". Note: Other HTTP request methods, such as put and DELETE, are also available, but only partially supported by browsers.
Timeout Number Sets the request timeout (in milliseconds). This setting overrides the global setting.
Async Boolean (Default: TRUE) The default setting is that all requests are asynchronous requests. If you need to send a sync request, set this option to false. Note that the synchronization 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.
The options for this AJAX request}
Cache Boolean (default: TRUE) JQuery 1.2 new functionality, set to false will not load request information from the browser cache.
Complete Function The callback function (called when the request succeeds or fails) after the request completes. Parameters: XMLHttpRequest Object, Success message string.
The options for this AJAX request}
ContentType String (Default: "application/x-www-form-urlencoded") the content encoding type when sending information to the server. Default values are appropriate for most applications.
Data Object,
String
Data sent to the server. is automatically converted to the request string format. The GET request is appended to the URL. View the ProcessData option description to prevent this automatic conversion. Must be in the Key/value format. If you are an array, JQuery will automatically correspond to the same name for different values. such as {foo:["bar1", "Bar2"]} is converted to ' &foo=bar1&foo=bar2 '.
DataType String

The type of data expected to be returned by the server. If not specified, JQuery will automatically return Responsexml or responsetext based on the HTTP packet MIME information and pass as a callback function parameter, available values:

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

HTML: Returns plain text HTML information, including script elements.

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

"JSON": Returns JSON data.

"JSONP": Jsonp format. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? To the correct function name to execute the callback function.

Error Function (Default: Automatic judgment (XML or HTML)) This method is called when a request fails. This method has three parameters: the XMLHttpRequest object, the error message, and (possibly) the error object being caught.
The options for this AJAX request}
Global Boolean (default: TRUE) triggers a global AJAX event. 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) gets new data only when the server data changes. Use HTTP packet last-modified header information to determine.
ProcessData Boolean (default: TRUE) by default, the data sent 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 Function callback function after successful request. This method has two parameters: the server returns the data, returns the status
The options for this AJAX request}

Here are a few Ajax event parameters: Beforesend, Success, complete, error. We can define these events to deal well with each of our AJAX requests. Notice that this in these AJAX events is the information about the options for the Ajax request (refer to the picture of this when you say Get () method).

The code is as follows

$.ajax ({
 url:url,
 dataType: ' json ',
 data:data,
 success:callback
});

You may not have used JSON data, my little station has mentioned the use of JSON several times, if you are not familiar with the JSON format, you can look at the jquery mobile ListBox value, jquery under the use of JSON example

Get JSON data

This will randomly display a JSON data. So far we have summed up the five shorthand methods of Jquery.ajax, and then let's focus on the Jquery.ajax () method, which is often used by the author Jquery.ajax (), because in most cases, We need to capture and process an error in the AJAX request.

6.jquery.ajax ()

The Jquery.ajax () method is used to get the data, and a common writing is given below, and the corresponding annotation is made.

The code is as follows

$.ajax ({
 URL: "http://www.hzhuti.com",//requested URL address
 dataType: "JSON",//Return format is JSON
 async:true,//request is asynchronous, The default is asynchronous, which is also an important feature
 of AJAX data: {"id": "Value"},//Parameter value
 type: "Get",//Request mode
 beforesend:function () {
  //processing before request c10/>},
 success:function (req) {
  //Request successful processing
 },
 complete:function () {
  //Request completed processing
 },
 error:function () {
  //Request error handling
 }
});

Using Jquery.ajax ()

The data will be displayed here

$.ajax My Actual application example

//1.$.ajax asynchronous request with JSON data var AJ = $.ajax ({url: ' productmanager_reverseupdate ',//jump to Acti 
    On 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 table contents As String asynchronous request function Notips () {var Formparam = $ ("#form1"). Serialize (); The serialized table content is a string $.ajax ({type: 
  ' Post ', url: ' Notice_notipsnotice ', Data:formparam, Cache:false, DataType: ' JSON ', success:function (data) { 
} 
 }); 
  //3.$.ajax asynchronous request for stitching URL var yz=$.ajax ({type: ' post ', url: ' validatepwd2_checkpwd2?password2= ' +password2, data:{}, Cache:false, DataType: ' JSON ', success:function (data) {if (data.msg = = "false")//server returns FALSE, will Validatepasswor The value of D2 is changed to Pwd2error, which is asynchronous and needs to consider the return time {textpassword2.html ("<font color= ' red ' > Business password is incorrect!") 
    </font> "); 
    $ ("#validatePassword2"). Val ("Pwd2error"); 
    CheckPassword2 = false; 
   Return
}}, Error:function () {}}); 4.$.ajax the asynchronous request to splice data $.ajax ({URL: ' <%=request.getcontextpath ()%>/kc/kc_checkmernameunique.action ', type: ' 
 Post ', data: ' Mername= ' +values, Async:false,//default to True asynchronous Error:function () {alert (' Error '); }, Success:function (data) {$ ("#" +divs). HTML (data); }
});

The jquery Ajax usage of this article is summed up here, and there are some methods that are not fully summarized. such as Ajaxstart (), Ajaxstop (), and so on, in the future use, I will summarize them.

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.