Deep understanding of Ajax in jquery

Source: Internet
Author: User
Tags getscript http post object serialization

jquery provides some of the quick things you need to do in your daily development, such as load, Ajax, get, and post, and developing Ajax with jquery will be extremely straightforward. This allows developers to focus on the business and user experience without having to bother with the tedious XMLHttpRequest object. jquery encapsulates Ajax operations, $.ajax () the lowest-level method in jquery, 2nd is the load (), $.get (), and $.post () methods, and layer 3rd is the $.getscript () and $.getjson () methods. The Ajax in jquery is described in detail below

Load ()

The load () method is the simplest and most commonly used Ajax method in jquery, using the Load () method to load data from the server via an AJAX request, and to place the returned data in the specified element

"Call format"

The call format of the load () method is as follows, the parameter URL is the load server address, the option data parameter is a request to send, the callback parameter is a successful data request, the execution of the callback function

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

"Load HTML Document"

$ (' #result '). Load (' ajax/test.html ');

[note] If the selector does not have a matching element, such as document does not contain id= "result" element, this Ajax request will not be sent out

<!--current page--><script src= "Http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js" ></script>< style>h6{margin:4px;} p{margin:0;} </style><body><input type= "button" id= "Send" value= "Ajax get" >   <div class= "comment" > Comments available : </div><div id= "ResText" ></div><script>$ (function () {    $ (' #send '). Click (function () {        $ (' #resText '). Load (' ajaxjqueryload.html ')})    </script><!--page to load--><div class= "comment" >    

"Partial Loading"

If the URL parameter's string contains one or more spaces, then the content after the first space is considered a jquery selector, which determines which part of the returned result should be loaded

$ (' #result '). Load (' ajax/test.html #container ');

When this method executes, it retrieves the contents of the page returned by ajax/test.html, jquery gets the contents of the ID container element, and inserts it into the ID as the result element, while the other elements that are not retrieved are discarded

$ (function () {    $ (' #send '). Click (function () {        $ (' #resText '). Load (' ajaxjqueryload.html. para ')})    

"Delivery Method"

The load () method uses the Get method by default, and if the data parameter provides an object, use the Post method

No parameter is passed, which is the Get method $ (' #resText '). Load (' tset.php ')//parameter pass, then the post mode $ (' #resText '). Load (' tset.php ', {name: ' Rain ', Age: ' 22 '})

"Callback function"

If a "complete" callback function is provided, it will be called after the function has finished processing and the HTML has been inserted. The callback function is called once on each matching element, and this always points to the DOM element that is currently being processed

The callback function has 3 parameters that represent the content returned by the request, the request status, and the XMLHttpRequest object, respectively

$ (' #result '). Load (' ajax/test.html ', function (responsetext,textstatus,xmlhttprequest) {  //responsetext: Request returned content  //teststatus:success, error, notmodified, timeout four  //xmlhttprequest:xmlhttprequest objects});
<style>h6{margin:4px;} p{margin:0;} #test {border:1px solid black;} </style><input type= "button" id= "Send" value= "Ajax get" >   <div class= "comment" > Comments available: </div ><div id= "ResText" ></div><div id= "test" ></div><script>$ (function () {    $ (' # Send '). Click (function () {        $ (' #resText '). Load (' ajaxjqueryload.html. Para ', function (a,b,c) {            $ (' #test '). HTML (' ResponseText: ' + A + ' <br>textstatus: ' + B + ' <br>xmlhttprequest: ' + c);})})    </script>

Getjson ()

The Getjson () method loads JSON-encoded data from the server using an HTTP GET request

"Call format"

The invocation format of the Getjson () method is as follows. Where the URL parameter is the server address for the request to load the JSON-formatted file, the option data parameter is the one sent at the request, the callback parameter is the callback function that executes after the data request succeeds

$.getjson (Url,[data],[callback])

The Getjson () method is equivalent to the abbreviation of the following Ajax () method

$.ajax ({  dataType: "JSON",  Url:url,  data:data,  success:success});

"Callback function"

The first parameter in a callback function represents the returned data

$.getjson (' Test.json ', function (data) {    //data: Data returned})

In general, use the each () method to construct the DOM structure

<input id= "btnshow" type= "button" value= "Load"/><div id= "result" ></div><script>$ (' #btnShow ') . Click (function () {    var $this = $ (this);    var $html = ';    $.getjson (' Sport.json ', function (data) {        $this. attr (' disabled ', ' true ');        $.each (Data,function (index,sport) {            $html + = ' <div> ' + sport[' name '] + ' </div> ';        });        $ (' #result '). HTML ($html);    })}) </script>

The JSON file is as follows

[{   "name": "Football"},{   "name": "Walk"},{   "name": "Basketball"},{   "name": "Table Tennis"},{   "name": "Cycling"}]

GetScript ()

The GetScript () method loads and executes a JavaScript file from the server using an HTTP GET request

The GetScript () method call format is as follows, the parameter URL is the server request address, the optional callback parameter is the callback function executed after the request succeeds

$.getscript (Url,[callback])

Equivalent to an abbreviation for an AJAX function

$.ajax ({  url:url,  dataType: "Script",  success:success});
<input id= "btnshow" type= "button" value= "Load"/><div id= "result" ></div><script>$ (' #btnShow ') . Click (function () {    var $this = $ (this);    $.getscript (' Sport.js ', function () {        $this. attr (' disabled ', ' true ');        $ (' #result '). HTML ($html);    })}) </script>

JS file as follows

var data = [{"Name": "Soccer"}, {"name": "Walk"}, {"name": "Basketball"}, {"Name"    : "Table Tennis"}, {"Name": "    Cycling"}] var $html = '; $.each (data, function (index, sport) {$html +     = "<div>" + sport["name"] + "</div>";});

Get ()

The Get () method loads data from the server using an HTTP GET request

"Call format"

The call format of the Get () method is as follows, and the URL represents a URL string that contains the sending request; Data represents a string or Key/value key value pair sent to the server; Success (data, Textstatus, JQXHR) Represents the callback function executed when the request succeeds; datatype represents the expected data type returned from the server. Default: Smart guessing (XML, JSON, script, or HTML)

Jquery.get (URL [, data] [, Success (data, Textstatus, JQXHR)] [, DataType])

Equivalent to an abbreviation for an AJAX function

$.ajax ({  url:url,  data:data,  success:success,  datatype:datatype});

"Use parameters"

The Key/value data sent to the server through the Get () method is eventually appended to the URL as a query string

<form action= "#" id= "Form1" >    <p> comments:</p>    <p> name: <input type= "text" name= "username "id=" username "></p>    <p> Contents: <textarea  name=" content "id=" Content "rows=" 2 "cols=" > </textarea></p>    <p><input type= "button" id= "send" value= "Submit" ></p></form> <div class= "comment" > commented:    <div id= "ResText" ></div></div><script>$ (' #send '). Click (function () {    $.get (' jqget.php ', {        username:$ (' #username '). Val (),        content:$ (' #content '). Val ()    },function (data) {        //    })}) </script>

"Callback function"

function (data,textstatus) {    //data: The returned content may be XML, JSON, HTML, JS    //textstatus:success, error, notmodified, Timeout four Kinds}

"Data Format"

1. HTML Fragment

function (data,textstatus) {    $ (' #resText '). HTML (data);}

2. XML document

function (data,textstatus) {    var username = $ (data). Find (' comment '). attr (' username ');    var content = $ (data). Find (' comment content '). text ();    var txthtml = "<div class= ' comment ' >

3. JSON

function (data,textstatus) {    var username = data.username;    var content =  data.content;    var txthtml = "<div class= ' comment ' >
<!--front page--><select id= "num" >    <option value= "1" >1</option>    <option value= "2" >2</option>    <option value= "3" >3</option>    <option value= "4" >4</option> </select><button id= "Send" > Test </button><div id= "result" ></div><script>$ (' # Send '). Click (function () {    $.get (' jqrequest.php ', {        num: $ (' #num '). Val ()    },function (data) {        $ (' # Result '). HTML (' you select the number ' + $ (' #num '). Val () + ' is ' + data} ')    }) </script><!--back-end page--><?php $num = $_reques t[' num '];if ($num% 2 = = 0) {    echo ' even ';} else{    echo ' odd ';}? >

Post ()

The post () method loads data from the server using an HTTP POST request

Jquery.post (URL [, data] [, Success (data, Textstatus, JQXHR)] [, DataType])

Equivalent to the shorthand form of an Ajax function

$.ajax ({  type: "POST",  Url:url,  data:data,  success:success,  datatype:datatype});
<!--front page--><select id= "num" >    <option value= "1" >1</option>    <option value= "2" >2</option>    <option value= "3" >3</option>    <option value= "4" >4</option> </select><button id= "Send" > Test </button><div id= "result" ></div><script>$ (' # Send '). Click (function () {    $.post (' jqrequest.php ', {        num: $ (' #num '). Val ()    },function (data) {        $ (' #result '). HTML (' you select the number ' + $ (' #num '). Val () + ' is ' + data} ')    }) </script><!--backend page--><?php $num = $_requ est[' num '];if ($num% 2 = = 0) {    echo ' even ';} else{    echo ' odd ';}? >

The post () method and The Get () method are both structured and used in the same way. Note, however, that when the load () method is passed with a data parameter, the request is sent using the Post method

Serialization of

When there are more fields in a form, and the form elements are more complex, you need a way to simplify the operation of extracting the values of the internal controls of the form, which is usually called serialization, and JQuery provides three methods of Param (), serialize (), and Serialzearray ()

"Param ()"

The Param (obj) method is used to create an array or object serialization string, which applies to a URL address query string or AJAX request

Console.log ($.param ({width:1680, height:1050});//' width=1680&height=1050 '

"Serialize ()"

The serialize () method compiles the value of the form element used as a submission into a string

[Note an additional benefit of the]serialize () method is that the special characters in the key-value pairs are automatically encoded

<form> <select name= "single" > <option>Single</option> <option>Single2</option> </select> <br/> <select name= "multiple" multiple= "multiple" > <option selected= "selected" >m ultiple</option> <option>Multiple2</option> <option selected= "selected" >multiple3</ option> </select> <br/> <input type= "checkbox" name= "Check" value= "Check1" id= "Ch1"/> <label For= "Ch1" >check1</label> <input type= "checkbox" name= "Check" value= "Check2" checked= "Checked" id= "CH2"/ > <label for= "CH2" >check2</label> <br/> <input type= "Radio" name= "Radio" value= "Radio1" check Ed= "Checked" id= "r1"/> <label for= "R1" >radio1</label> <input type= "Radio" name= "Radio" value= " Radio2 "id=" R2 "/> <label for=" R2 ">radio2</label></form><p><tt id=" Results "></ tt></p><script> function ShowvalUEs () {$ ("#results"). Text ($ ("form"). Serialize ());    } $ (": CheckBox,: Radio"). Click (showvalues);    $ ("select"). Change (ShowValues); ShowValues ();</script>

"Serializearray ()"

The Serializearray () method compiles the values that are used as the submitted form elements into an array of name and value objects, which are JSON-formatted data. For example [{name:a value:1}, {name:b value:2},...]

<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> <script>$ (' form '). Submit (function () {  Console.log ($ (this). Serializearray ());  return false;}); </script>

The results are as follows

[  {    name: ' A ',    value: ' 1 '  },  {    name: ' B ',    value: ' 2 '  },  {    name: ' C ',    Value: "3"  },  {    name: "D",    Value: "4"  },  {    name: "E",    Value: "5"  }]

The object can use the each () function to iterate over the output of the data

$DATAARR = $ (' form '). Serializearray (); $html = "; $.each ($DATAARR, function (i,data) {    $html + = data.name + ': ' + Data.value + '; ';}) Console.log ($html);//a:1;b:2;c:3;d:4;e:5;

Ajax ()

The methods described previously for load (), get (), post (), GetScript (), Getjson () are all implemented based on the Ajax () method.

The Ajax () method is the lowest-level, most powerful method of requesting server data, not only to get the data returned by the server, but also to send a request to the server and pass a numeric value, which is called in the following format:

$.ajax ([Settings])

Where the parameter settings is the configuration object when the AJAX request is sent, in which the URL represents the path requested by the server, data is passed at the request, datatype is the data type returned by the server, success is the callback function for the successful execution of the request, Type is the way to send data requests by default to get

The common parameters are as follows

The name Value/Description Async Boolean value that indicates whether the request is processed asynchronously. The default is true. Beforesend (XHR) The function that runs before the request is sent. The cache Boolean value that indicates whether the browser caches the requested page. The default is true. The function that is run when complete (Xhr,status) requests are completed (called after the request succeeds or fails, that is, after the success and the error function) ContentType The content type to use when sending the data. By default, the "application/x-www-form-urlencoded" context specifies the "this" value for all AJAX-related callback functions. Data is defined to be sent to the server. Datafilter (Data,type) functions for handling XMLHttpRequest raw response data. DataType the data type of the expected server response. Error (XHR,STATUS,ERROR) If the request fails the function to run. Global Boolean value that specifies whether to trigger an overall AJAX event handler for the request. The default is true. Ifmodified Boolean value that specifies whether the request succeeds only if the response has changed since the last request. The default is False. Jsonp A string that overrides the callback function in a JSONP. JSONPCALLBACK Specifies the name of the callback function in a JSONP. password Specifies the password that is used in HTTP access authentication requests. ProcessData Boolean value that specifies whether the data sent through the request is converted to a query string. The default is true. SCRIPTCHARSET specifies the requested character set. Success (RESULT,STATUS,XHR) The function that runs when the request succeeds.  Timeout                   Sets the local request time-out (in milliseconds). Traditional Boolean value that specifies whether to use the traditional style of parameter serialization. Type specifies the kind of request (GET or POST). The URL specifies the URL to send the request. The default is the current page. USERNAME Specifies the user name to use in HTTP access authentication requests. XHR the function used to create the XMLHttpRequest object.
<!--front page--><select id= "num" >    <option value= "1" >1</option>    <option value= "2" >2</option>    <option value= "3" >3</option>    <option value= "4" >4</option> </select><button id= "Send" > Test </button><div id= "result" ></div><script>$ (' # Send '). Click (function () {    $.ajax ({      URL: ' jqrequest.php ',      type: ' POST ',      data:{        num:$ (' #num '). Val ()      },      success:function (data) {        $ (' #result '). HTML (' you select the number ' + $ (' #num '). Val () + ' is ' + data ')      }    ) }) </script> <!--backend page--><?php $num = $_request[' num '];if ($num% 2 = = 0) {    echo ' even ';} else{    echo ' odd ';}? >

Global events

jquery simplifies AJAX operations not only in terms of calling Ajax methods and handling responses, but also in controlling HTTP requests in the process of invoking Ajax methods. Some of the custom global functions provided by jquery enable you to register callback functions for various AJAX-related events. For example, when the AJAX request starts, the callback function of the Ajaxstart () method is triggered, and the callback function of Ajaxstop () is triggered when the AJAX request ends. These methods are global, so no matter where the code that created them is located, they are triggered whenever an AJAX request occurs.

"Ajaxsetup ()"

The Ajaxsetup () method sets the default value for the AJAX request to be used later, and after the setting is complete, subsequent AJAX requests will not need to add these option values, which are called in the following format:

$.ajaxsetup ([options])

For example, set the default address for the AJAX request to "/xmlhttp/" and POST instead of the default GET method. Subsequent AJAX requests no longer set any option parameters

$.ajaxsetup ({   URL: "/xmlhttp/",   Type: "POST"}); $.ajax ({data:mydata});

If you want an AJAX request to be unaffected by the Ajaxsetup () method, you can set the global in the parameter to False when using the Ajax () method

$.ajaxsetup ({   URL: "/xmlhttp/",   Type: "POST"}), $.ajax ({  global:false,  URL: "Test",  type: ' GET ' })

"Ajaxstart () and Ajaxstop ()"

The Ajaxstart () and Ajaxstop () methods are bound Ajax events. The Ajaxstart () method is used to trigger a function before the AJAX request is issued, and the Ajaxstop () method is used to trigger the function after the AJAX request is completed. Their invocation format is

$ (selector). Ajaxstart (function ()) $ (selector). Ajaxstop (function ())

[note] Starting with jQuery 1.8, the Ajaxstart () and Ajaxstop () methods can only be bound to the document element

For example, reading a remote Web site picture may be slow, if in the process of loading, do not give users some hints and feedback information, it is easy to let users mistakenly think that button click Useless, so that users lose confidence in the site. At this point, the Ajaxstart () and Ajaxstop () methods came in handy.

<!--front page--><select id= "num" >    <option value= "1" >1</option>    <option value= "2" >2</option>    <option value= "3" >3</option>    <option value= "4" >4</option> </select><button id= "Send" > Test </button><div id= "Result" ></div><script>$ ( Document). Ajaxstart (function () {    $ (' #test '). Show ()}). Ajaxstop (function () {    $ (' #test '). Hide ();}); $ (' #send '). Click (function () {    $.ajax ({      URL: ' jqrequest.php ',      type: ' POST ',      data:{        num:$ (' # Num '). val ()      },      success:function (data) {        $ (' #result '). HTML (' you select the number ' + $ (' #num '). Val () + ' is ' + data ';      }    })}) </script> <!--backend page--><?php $num = $_request[' num '];if ($num% 2 = = 0) {    echo ' even ';} else{    echo ' odd ';}? >

In-depth understanding of 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.