Ajax in jquery

Source: Internet
Author: User
Tags getscript browser cache

Load () method

Load (Url,[data],[callback])

URL is the page address that is loaded

Data represents the information sent to the server in the format key/value

The callback format is: function (responsetext,textstatus,xmlhttprequest) {}

ResponseText: Request What is returned

Textstatus: Request Status: Success, error, notmodified, timeout these 4 kinds

Xmlhttprequest:xmlhttprequest Object

The load () method is passed as specified according to the parameter data. If there is no parameter passing, it is passed by get, and vice versa, it is automatically converted to post mode

$ ("#div1"). Load ("jsp/feed.jsp",    //if "jsp/feed.jsp  . Filterclass", means to get all the elements of the JSP page with the class name Filterclass {      NAME:CLF,      Age  : 25//tested, variable names quoted, single quotes, no quotes, the background can be taken to the value//If it contains Chinese, must be encoded with encodeURI (), and then the server side with decodeURI () decoding, such as//{ Name:encodeuri ($ ("#uName"). Val ()), "Password": $ ("#uPassword"). Val ()},},  //can also be used with array values, {"attr []", ["CLF", "25", " Male "]}function () {      $ (" #div2 "). Text (" AJAX ");});

$ ("div"). Load ("Wrongname.xml", function (RESPONSE,STATUS,XHR) {      if (status== "Success")      {              $ ("div"). html ("<ol></ol>");              $ (response). Find ("Artist"). each (function () {              <span style= "White-space:pre" ></span>varitem_text = $ (this). text ();              <span style= "White-space:pre" ></span>$ (' <li></li> '). HTML (item_text). AppendTo (' ol ');       <span style= "White-space:pre" ></span>      });      }      Else      {               $ ("div"). html ("Anerror occured: <br/>" + xhr.status + "+ xhr.statustext)      }    });

Getjson () method

Getjson (Url,[data],[callback])

Callback format is function (Data,textstatus) {}

Data is a returned JSON object

$.getjson ("Test.js", {name: "John", Time: "2pm"}, function (JSON) {  alert ("JSON Data:" +json.users[3].name);});

GetScript () method

GetScript (Url,[callback])

Callback format as function (Response,status)

Response-Contains the result data from the request

Status-Contains the requested State ("Success", "Notmodified", "Error", "timeout", or "ParserError")

Scripts injected through this function are automatically executed

Get () method

Get (Url,data,callback (RESPONSE,STATUS,XHR), DataType)

DataType possible types: "XML", "HTML", "text", "script", "JSON", "JSONP"

The Get () method loads information through a remote HttpGet request.

Post () method

Post (Url,data,callback (RESPONSE,STATUS,XHR), DataType)

Similar to the Get () method

The Get () method is not suitable for passing data with a large amount of data, and its requested historical information is stored in the browser's cache, with a certain risk, while the post () method does not exist.

Serialize () method

The serialize () method creates a URL-encoded text string by serializing the form value.

You can select one or more form elements (such as input and/or text boxes), or the form element itself.

The serialized value can be used in the URL query string when generating an AJAX request.

<form>  <div><input type= "text" Name= "a" value= "1" id= "a"/></div>  <div>< Input type= "text" name= "B" value= "2" id= "B"/></div>  <div><input type= "hidden" name= "C" value= "3 "Id=" C "/></div>  <div>    <textarea name=" D "rows=" 8 "cols=" + ">4</textarea>  </div>  <div><select name= "E" >    <option value= "5" selected= "selected" >5</option >    <option value= "6" >6</option>    <option value= "7" >7</option>  </select ></div>  <div>    <input type= "checkbox" Name= "F" value= "8" id= "F"/>  </div>  <div>    <input type= "Submit" name= "G" value= "Submit" id= "G"/>  </div></form>

$ (' form '). Submit (function () {  alert (this). Serialize ());  return false;});

Output a standard query string:

A=1&b=2&c=3&d=4&e=5

Note: Only successful controls are serialized as strings. If you do not use a button to submit the form, the value of the Submit button is not serialized. If the value of the form element is to be included in the sequence string, the element must use the Name property. When multiple items in a form are selected, the method can pass only one value

Ajax () method

1.url:

Requires that the requested address be sent as a parameter of type string (the current page address is assumed to be the default).

2.type:

A parameter of type string is required, and the request method (post or get) defaults to get. Note Other HTTP request methods, such as put and delete, can also be used, but only some browsers support it.

3.timeout:

Requires a parameter of type number to set the request time-out (in milliseconds). This setting overrides the global setting of the $.ajaxsetup () method.

4.async:

Requires a parameter of type Boolean, which is set to True by default and all requests are asynchronous requests. If you need to send a synchronization request, set this option to false. Note that the synchronization request locks the browser, and the user's other actions must wait for the request to complete before it can be executed.

5.cache:

A parameter that is required to be of type Boolean, which defaults to True (False when datatype is a script), and set to false will not load the request information from the browser cache.

6.data:

Requires data to be sent to the server as an object or a string of type parameters. If it is not already a string, it is automatically converted to a string format. 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 key/value format, for example {foo1: "Bar1", Foo2: "Bar2"} to &foo1=bar1&foo2=bar2. In the case of arrays, jquery automatically corresponds to the same name for different values. For example {foo:["Bar1", "Bar2"]} is converted to &FOO=BAR1&FOO=BAR2.

7.dataType:

Requires a parameter of type string that expects the 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. The following types are available:

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 When you make a remote request (not under the same domain), all post requests are converted to get requests.

JSON: Returns the JSON data.

JSONP:JSONP format. When a function is called using the Sonp form, for example Myurl?callback=?,jquery will automatically replace the latter "?" is the correct function name to execute the callback function.

Text: Returns a plain text string.

8.beforeSend:

Parameters that require a function type can modify the functions of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. If you return False in Beforesend, you can cancel this Ajax request. The XMLHttpRequest object is the only parameter.

  function (XMLHttpRequest) {this               ;   The options parameter passed when calling this Ajax request            }

9.complete:

A parameter that is required to be a function type, called when the request is complete (invoked when the request succeeds or fails). Parameters: The XMLHttpRequest object and a string that describes the successful request type.

function (XMLHttpRequest, textstatus) {this             ;   The options parameter passed when calling this Ajax request          }

10.success: Requires a parameter of type function, callback function called after successful request, there are two parameters.

(1) The 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, and so on            ;  The options parameter passed when calling this Ajax request         }

11.error:

The function that is called when the request fails with a parameter that is required as a function type. The function has 3 parameters, the XMLHttpRequest object, the error message, and optionally the error object being captured. The Ajax event functions are as follows:

       function (XMLHttpRequest, textstatus,errorthrown) {          //normally textstatus and Errorthrown only one contains the information this          ;   The options parameter passed when calling this Ajax request       }

12.contentType:

A parameter of type string is required, and when the message is sent to the server, the content encoding type defaults to "application/x-www-form-urlencoded". This default value is suitable for most applications.

13.dataFilter:

A function that requires the preprocessing of the original data returned by Ajax, as a parameter of the function type. Provides data and type two parameters. Data is the original data returned by Ajax, and type is the datatype parameter that is provided when Jquery.ajax is called. The value returned by the function will be further processed by jquery.

            function (data, type) {                //returns data returned after processing                ;            }

14.dataFilter:

A function that requires the preprocessing of the original data returned by Ajax, as a parameter of the function type. Provides data and type two parameters. Data is the original data returned by Ajax, and type is the datatype parameter that is provided when Jquery.ajax is called. The value returned by the function will be further processed by jquery.

            function (data, type) {                //returns data returned after processing                ;            }

15.global:

Requires a parameter of type Boolean, which is true by default. Indicates whether global AJAX events are triggered. Setting to FALSE will not trigger global AJAX events, Ajaxstart or ajaxstop can be used to control various AJAX events.

16.ifModified:

A parameter of type Boolean is required, and the default is False. Get new data only when the server data changes. Server data changes are based on the last-modified header information. The default value is False, which ignores header information.

17.JSONP:

Requires a parameter of type string to override the name of the callback function in a JSONP request. This value is used instead of the "callback=?" The "callback" part of the URL parameter in this get or POST request, such as {jsonp: ' onjsonpload ', causes the "onjsonpload=?" passed to the server.

18.username:

A parameter of type string that is required to respond to the user name of the HTTP access authentication request.

19.password:

A parameter of type string that is required to respond to the password for HTTP access authentication request.

20.processData:

Requires a parameter of type Boolean, which is true by default. 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.

21.scriptCharset:

A parameter of type string is required and is used to force the character set (charset) only if the request is datatype as "JSONP" or "script" and the type is get. Typically used when local and remote content encodings are different.

$.ajax ({      type: "GET",      URL: "Test.json",      data:{username:$ ("#username"). Val (), content:$ ("#content"). Val ()},      DataType: "JSON",      success:function (data) {             $ (' #resText '). empty ();                                                                             varhtml = ";             $.each (Data,function (commentindex, comment) {             html + = comment[' username ']  + comment[' content '                        );});               }   });

$.ajaxsetup () method

When using the Ajax () method, it is sometimes necessary to call multiple $.ajax () methods, which can be cumbersome if each method sets the request details. To simplify this work, you can use the Ajaxsetup () function in jquery to set global Ajax default options, once set, globally valid

$.ajaxsetup ({      type: "GET",      URL: "jsp/response.jsp",      dataType: "xml"});

After that, the Ajax () function is called, and the parameters set above are used by default

Ajaxstart () and Ajaxstop () and other global events

The former is when a request starts executing, and is often used to write some preparatory work, such as the word "getting data ...", which is triggered at the end of the request and is often used in conjunction with the former. If you change the prompt to "data has been successfully obtained!" "And then fade away

$ ("#my"). Ajaxstart (function () {              $ (this). Show ();          }). Ajaxstop (function () {            $ (this). Hide ();          


<div id= "My" style= "Display:none" >    

Ajaxstart () and Ajaxstop () are global functions, and in addition, there are 4 AJAX-related global events in jquery

Ajaxcomplete () executes the function when the AJAX request is complete

Ajaxerror () execute function when an AJAX request error occurs

Ajaxsuccess () executes the function when the AJAX request succeeds

Ajaxsend () executes the function at the beginning of the AJAX request

$ ("#msg"). Ajaxerror (function (event,request,settings) {     $ (this). Append ("<li> error page:" + Settings.url + "</ Li> ");});


Ajax in jquery

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.