Ajax in jquery

Source: Internet
Author: User
Tags getscript

Load () method

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

URL is the loaded page address

Data represents the information sent to the server. Format is 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 on its own initiative according to the data of the parameter. Assume that no parameters are passed. is passed in Get mode. Conversely, it is self-actively converted to post mode

$ ("#div1"). Load ("jsp/feed.jsp",    //assuming "jsp/feed.jsp  . Filterclass", which means to get all the elements of the JSP page with the class name Filterclass {      NAME:CLF,      Age  : 25//test, variable name plus, single-cited, no-cited, the background can be taken to the value//hypothesis contains Chinese, must be encoded with encodeURI (). And then the server side with decodeURI () decoding can be. such as//{Name:encodeuri ($ ("#uName"). Val ()), "Password": $ ("#uPassword"). Val ()},},  //can also be used to pass values to the array. {"attr []", ["CLF", "+", "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-includes result data from the request

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

Scripts injected through this function will run on their own initiative

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 at the same time, its requested historical information is saved in the browser's cache. There is a certain risk, and the post () method does not present this deficiency

Serialize () method

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

The ability to 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

Gaze: Only the "successful control" is serialized as a string. Assuming that the form is not submitted by using the button, the value of the button is serialized incorrectly.

Assume that the value of the form element is included in the sequence string. The element must use the Name property. When multiple items in a form are selected, the method can only pass the value of one item

Ajax () method

1.url:

The requirement is a parameter of type string. (Default to the current page address) to send the requested address.

2.type:

Requires a parameter of type string, the request mode (post or get) default feeling get. Note the other HTTP request methods. For example, 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:

A parameter that is required as a Boolean type. The default setting is true, and all requests are asynchronous requests.

Suppose you need to send a synchronization request. Please set this option to false.

Attention. The sync request will lock the browser, and the user's other actions must wait for the request to complete.

5.cache:

Required to be a Boolean parameter, the default is true (when datatype is script, it defaults to false). Set to False to not load the request information from the browser cache.

6.data:

The data sent to the server is required for a parameter of type object or string.

Assuming that it is not a string, you are actively converting yourself to a string format. The GET request will be appended to the URL. Prevent such self-conversions and be able to view the ProcessData option. The object must be in the Key/value format, such as {foo1: "Bar1", Foo2: "Bar2"} to &foo1=bar1&foo2=bar2.

If it is an array, jquery will take its own initiative to have the same name for different values. For example {foo:["Bar1", "Bar2"]} is converted to &FOO=BAR1&FOO=BAR2.

7.dataType:

The requirement is a parameter of type string. Expected data type returned by the server.

Assumptions are not specified. jquery will voluntarily return Responsexml or responsetext based on the HTTP packet mime information. and is passed as a callback function parameter.

The available types are as follows:

XML: Returns an XML document. Available with jquery.

HTML: Returns plain text HTML information, including script tags that run when the DOM is inserted.

Script: Returns plain text JavaScript code. Do not actively cache the results themselves. Unless the cache parameter is set. Note When a remote request is not in the same domain. All post requests are converted to get requests.

JSON: Returns the JSON data.

JSONP:JSONP format. When calling a function using the Sonp form, such as Myurl?

Callback=?. jquery will take its own initiative to replace the latter one "?

"is the correct function name. To run the callback function.

Text: Returns a plain text string.

8.beforeSend:

The number of parameters required for the function type. A function that can alter the XMLHttpRequest object before sending the request. For example, add yourself to define HTTP headers. It is assumed in Beforesend to return False to cancel this Ajax request. The XMLHttpRequest object is the only number of parameters.

  function (XMLHttpRequest) {this               ;   Options that are passed when calling this Ajax request            }

9.complete:

The request is a parameter of the function type, and the callback function that is called when the request is complete (called when the request succeeds or fails). Parameters: XMLHttpRequest object and a string describing the type of successful request.

function (XMLHttpRequest, textstatus) {this             ;   Options that are passed when calling this Ajax request          }

10.success: The request is a function-type parameter, and the callback function called after the request succeeds, there are two of the parameters.

(1) The data returned by the server and processed according to the datatype parameters.

(2) A string describing the state of the narrative.

         function (data, textstatus) {            //data may be xmldoc, jsonobj, HTML, text, and so on            ;  Options that are passed when calling this Ajax request         }

11.error:

The number of parameters required for the function type. The function that was called when the request failed. The function has 3 parameters, that is, the XMLHttpRequest object, the error message, and optionally, the captured Error object. Ajax event functions such as the following:

       function (XMLHttpRequest, textstatus,errorthrown) {          //normally textstatus and Errorthrown have only one of them including information this          ;   Options that are passed when calling this Ajax request       }

12.contentType:

The requirement is a parameter of type string. When sending information 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 parameters of a function type to preprocess the original data returned by Ajax. Provides data and type two parameters.

Data is the original data returned by Ajax, and the 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:

The number of parameters required for the function type. A function to preprocess the raw data returned by Ajax. Provides data and type two parameters. Data is the original information returned by Ajax. The 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:

Required to be a Boolean-type parameter, default is true. 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 expected to be false. Get new data only when the server data changes. The server data change inference is based on the last-modified header information.

The default value is False, which ignores header information.

17.JSONP:

Requires that the name of the callback function be overridden in a JSONP request for a parameter of type string. This value is used instead of the "callback=?" Such a GET or POST request in the "callback" section of the URL parameter, such as {jsonp: ' onjsonpload '} will cause the "onjsonpload=?" passed to the server.

18.username:

The requirement is a parameter of type string. The username used to respond to HTTP access authentication requests.

19.password:

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

20.processData:

Required to be a Boolean-type parameter, default is true.

By default. The data sent will be converted to an object (technically not a string) to match the default content type "application/x-www-form-urlencoded". Suppose you want to send DOM tree information or other information that you do not want to convert. Please set it to false.

21.scriptCharset:

A parameter of type string is required, only if the request is datatype as "JSONP" or "script". And the type is get when used to force the change character set (CharSet). Typically used at different times for local and remote content encoding.

$.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 '                        );});               }   });

Here is an example of an Ajax method operation XML

$.ajax (url: ' Example.xml ', DataType: ' xml ', success:function (data) {var $user = $ (data). Find ("user"); var strhtml = "Number:" + $user. attr ("id") + "<br/>"; strhtml + = "Name:" + $user. Children ("name"). Text () + "<br/>"; strHTML + + "Gender:" +$ User.children ("Sex"). Text () + "<br/>"; strhtml + = "Mailbox:" + $user. Children ("email"). Text () + "<br/>";});

<? XML version= "1.0" encoding= "Utf-8"?

><info> <user id= "10001" > <name>clf</name> <sex>male</sex> <email>[email protected]</email> </User></info>

$.ajaxsetup () method

When using the Ajax () method. Sometimes multiple $.ajax () methods need to be called. It would be a hassle to assume that each method sets the details of the request. In order to simplify this kind of work. In jquery, you can use the Ajaxsetup () function to set global AJAX default options. Settings once. Globally valid

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

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

Ajaxstart () and Ajaxstop () and other global events

The former is set off when the request starts to run. Often used to write some preparatory work, such as the word "getting data ...". The latter is triggered when the request ends 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 () Run the function when the AJAX request is complete

Ajaxerror () Run the function when an AJAX request error occurs

Ajaxsuccess () Run the function when the AJAX request succeeds

Ajaxsend () Run 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.