jquery Basics---Ajax basics
Content outline:
1.Ajax Overview
2.load () method
3.$.get () and $.post ()
4.$.getscript () and $.getjson ()
5.$.ajax () method
6. Serialization of Forms
Not easy, reproduced please indicate the source ~
A. Ajax Overview
The concept of Ajax was invented by Jesse James Garrett in 2005. It is not a single technology in itself, it is a collection of technologies, mainly:
1.JavaScript, capturing interactive behavior through user or other browser-related events;
A 2.XMLHttpRequest object that can send a request to the server without interrupting other browser tasks;
3. Files on the server, saving text data in XML, HTML, or JSON format;
4. Other JavaScript that interprets data from the server (such as PHP's data obtained from MySQL) and renders it on the page.
Because Ajax contains many features, the advantages and disadvantages are also obvious.
The main advantages of Ajax are the following points:
1. Plug-in support is not required (General browser and JavaScript is enabled by default);
2. User experience is excellent (can not refresh the page to obtain updatable data);
3. Improve the performance of the WEB program (in the delivery of data in order to relax on demand, not the overall submission);
4. Reduce the burden on the server and bandwidth (transfer some server operations to the client);
The lack of Ajax has the following points:
1. Different versions of browser degree XMLHttpRequest object support is insufficient (such as IE5);
2. The function of forward and backward is destroyed (because Ajax is always on the current page, there is no chance to the front and back page);
3. Search engine support is not enough (because the search engine crawler can not understand the content of JS caused by the change data);
4. Lack of development debugging tools (as opposed to other language toolset, JS or Ajax debugging development less poor).
The most critical place to use Ajax is to implement asynchronous requests, accept responses, and execute callbacks. So what's the difference between asynchronous and synchronous?
Our common Web program development is basically synchronous, meaning to execute a program in order to execute the next paragraph, similar to the call in the phone , a call to answer the next call, and asynchronous can perform multiple tasks at the same time, feel that there are many lines, similar to text messages , Don't stop accepting another text message because of reading a text message. Ajax can also be executed using synchronous mode, but the mode of synchronization is blocking mode, which will cause the execution of multiple lines and must be a single execution, the Web page will appear suspended animation, so the general Ajax mostly use asynchronous mode.
two. Load () method
JQuery does a lot of encapsulation of Ajax, and we use it more conveniently, without having to consider browser compatibility.
For encapsulation, JQuery uses a three-layer package:
The lowest-level encapsulation method is: $.ajax ();
The second layer encapsulates three methods:. Load (), $.get (), and $.post ();
The highest layer is the $.getscript () and $.getjson () methods.
The . Load () method has three parameters:
URL (must, request the URL address of the HTML file, the parameter type is String);
Data (optional, sent Key/value, parameter type is Object);
Callback (optional, successful or failed callback function with parameter type function).
If you want Ajax to load an HTML content asynchronously, we just need a URL for the HTML request.
Html
<input type= "button" value= "Get Data asynchronously"/>
<div id= "box" ></div>
Jquery
$ (' input '). Click (function () {
$ (' #box '). Load (' test.html ');
});
If you want to filter the loaded HTML, simply follow the URL parameter followed by a selector.
URL with Selector
$ (' input '). Click (function () {
$ (' #box '). Load ('test.html. my');
});
If it is a server file, such as. php. It is not only necessary to load data, but also to submit data to the server, so we can use the Second optional parameter, data.
There are two ways to submit data to the server: Get and post.
Do not pass data, the default is Get mode
$ (' input '). Click (function () {
$ (' #box '). Load ('test.php?url=googlexxx');
});
Get way to accept PHP code
<?php
if ($_get[' url '] = = ' googlexxx ') {
Echo ' Google ';
} else {
Echo ' Other sites ';
}
?>
To pass data, the POST method
$ (' input '). Click (function () {
$ (' #box '). Load (' test.php ', {
URL: ' Google '
});
});
The PHP code accepted by the Post method
<?php
if ($_post[' url '] = = ' Google ') {
Echo ' Google ';
} else {
Echo ' Other sites ';
}
?>
After the Ajax data is loaded, you can execute the callback function callback, which is the third parameter.
The callback function can also pass three optional parameters: responsetext (Request return), Textstatus (Request status), XMLHttpRequest (XMLHttpRequest object).
1 $ (' input '). Click (function () {2 3 $ (' #box '). Load (' test.php ', {4 5 URL: ' google ' 6 7 }, function (response, status, XHR) {8 9 alert (' return value: ' + response + ', Status: ' + status + ', State is: ' + xhr.statustext); 12 13});
Note: The status Gets the value if the data returned successfully is: success, otherwise: error. The XMLHttpRequest object belongs to the JavaScript category, and some properties can be called as follows:
If the data is returned successfully, then the StatusText property of the Xhr object returns the ' OK ' string. In addition to the ' OK ' status string, theStatusText property also provides a list of additional status description values, as follows:
three. $.get () and $.post ()
The. Load () method is a local method because he needs a JQuery object that contains an element as a prefix. While $.get () and $.post () are global methods, you do not need to specify an element. for use,. Load () is suitable for asynchronous fetching of static files, and $.get () and $.post () are more appropriate for parameters that need to be passed to the server page.
The $.get () method has four parameters, and the first three parameters, like. Load (), have a fourth parameter type, the content format that the server returns: including XML, HTML, script, JSON, JSONP, and text. The first parameter is a required parameter, and the next three is an optional parameter.
There are 3 ways to return HTML types asynchronously using $.get ():
1. By the second parameter, data, the string key value to the parameter
1 $ (' input '). Click (function () {2 3 $.get (' test.php ', ' url=googlexxx ', function (response, status, XHR) {4 5 $ (' # Box '). HTML (response); 6 7 }); 8 9});
2. Through the second parameter data, the object key value is passed to the parameter and then automatically converted to a question mark immediately following the argument
1 $ (' input '). Click (function () {2 3 $.get (' test.php ', {4 5 URL: ' googlexxx ' 6 7 },function (Response, status, XHR) {8 9 $ (' #box '). HTML (response); 12 13});
3. Pass a URL with a question mark immediately after the argument
1 $ (' input '). Click (function () {2 3 $.post (' test.php?url=googlexxx ', function (response, status, XHR) {4 5 $ (' # Box '). HTML (response); 6 7 }); 8 9});
PS: The fourth parameter type is the type that specifies the asynchronous return. In general, the type parameter is intelligent judgment, do not need us to set the initiative, if the active setting, it will be forced to return in the specified type format.
Using $.get () to return XML asynchronously
$ (' input '). Click (function () {
$.get (' test.xml ', function (response, status, XHR) {
$ (' #box '). HTML ($ (response). Find (' root '). Find (' URL '). text ());
}); Type is automatically converted to XML
});
PS: If an XML file is loaded, type will be judged intelligently. If you force the HTML type to return, the XML file will be returned as normal data without parsing the data in XML format.
Using $.get () to return JSON asynchronously
$.get (' Test.json ', function (response, status, XHR) {
Alert (response[0].url);
});
Using $.post () to return HTML asynchronously
1. Post submission cannot use question mark arguments, you can use a string as a key value pair to pass the parameter
1 $ (' input '). Click (function () {2 3 $.post (' test.php ', ' url=googlexxx ', function (response, status, XHR) {4 5 $ (' #box '). HTML (response); 6 7 }); 8 9 });
2. Post submissions can use object key value pairs
1 $ (' input '). Click (function () {2 3 $.post (' test.php ', {4 5 URL: ' Ycku ' 6 7 },function ( Response, status, XHR) {8 9 $ (' #box '). HTML (response); "html"); The data returned by the PHP file is plain text, the default is HTML or text12 13});
The use of $.post () method and $.get () are basically consistent, the difference between them is more obscure, the basic is the difference behind, in the user's use can not be reflected. The specific differences are as follows:
The 1.GET request is submitted through a URL, and the POST request is submitted by the HTTP message entity;
2.GET commit has a size limit (2KB), and the POST mode is unrestricted;
3.GET mode will be cached, there may be security issues, and POST does not have this problem;
4.GET is obtained via $_get[], POST via $_post[].
Four. $.getscript () and $.getjson ()
JQuery provides a set of methods for a specific asynchronous load:
$.getscript (), used to load a specific JS file;
$.getjson (), which is used to load JSON files specifically.
PS: In this way, you do not need the previous fourth parameter type!
Sometimes we want to be able to load the JS file in a specific situation, instead of loading all the JS files at the beginning, you can use the $.getscript () method.
Click the button and then load the JS file
$ (' input '). Click (function () {
$.getscript (' test.js ');
});
The $.getjson () method is specifically used to load the JSON file, using the same method as before.
$ (' input '). Click (function () {
$.getjson (' Test.json ', function (response, status, XHR) {
alert (Response[0].url);
});
});
Five $.ajax ()
$.ajax () is the lowest-level method in all Ajax methods, and all other methods are based on the encapsulation of the $.ajax () method. This method has only one parameter, passing an object of each function key-value pair.
$.ajax use
1 $ (' input '). Click (function () {2 3 $.ajax ({4 5 type: ' POST ',//here can be replaced by get 6 7 URL: ' test.php ') , 8 9 data: {Ten URL: ' googlexxx ' },14 success:function (response, Stutas, XHR) {16 17< c11/>$ (' #box '). HTML (response); }20 }); 22 23});
PS: For the Data property, if it is a GET mode, you can use three of the three forms previously said. If the post mode can use the previous two forms.
Six Serialization of Forms
The most common place for Ajax is the form operation, and the traditional form action is to submit the data to the server side via submit. If we use Ajax for asynchronous processing, we need to get each form element one after the other to commit. This will greatly reduce productivity.
form submission in regular form
1 $ (' form Input[type=button] '). Click (function () {2 3 $.ajax ({4 5 type: ' POST ', 6 7 URL: ' tes T.php ', 8 9 data: {Ten User: $ (' form Input[name=user] '). Val (), email: $ (' Form input[name=email ') '). Val () },16 success:function (response, status, XHR) { alert (response); }22 23} ); 24 25});
PS: The form element is very much in the case, it is very troublesome to write, error prone. When copying the submitted JS content, the Data property needs to be modified very much.
Use the form serialization method. Serialize (), which intelligently gets all the elements within the specified form. This way, when you face a large number of form elements, the contents of the form element are serialized into a string , and then the AJAX request is used.
Use. Serialize () to serialize the contents of the form
1 $ (' form Input[type=button] '). Click (function () {2 3 $.ajax ({4 5 type: ' POST ', 6 7 URL: ' tes T.php ', 8 9 Data: $ (' form '). Serialize (), success:function (response, status, XHR) { alert (re Sponse) (}16); 18 19}); 20 21
The serialize () method not only serializes elements within a form, but also directly retrieves content such as a radio box, a check box, and a drop-down list box.
Use serialization to get the selected element content
$ (': Radio '). Click (function () {
$ (' #box '). HTML (decodeuricomponent ($ (this). Serialize ()));
});
In addition to the. Serialize () method, there is also a method that you can use to return JSON data:. Serializearray (). This method can directly integrate data into a JSON object for key-value pairs.
$ (': Radio '). Click (function () {
Console.log ($ (this). Serializearray ());
var json = $ (this). Serializearray ();
$ (' #box '). HTML (json[0].value);
});
Sometimes, we may call the $.ajax () method multiple times in the same program. Many of these parameters are the same, and at this point we can use the $.ajaxsetup () provided by JQuery to request the default values to initialize the parameters.
1 $ (' form Input[type=button] '). Click (function () {2 3 $.ajaxsetup ({4 5 type: ' POST ', 6 7 URL : ' test.php ', 8 9 Data: $ (' form '). Serialize () (), $.ajax ({ success:function ( Response, status, XHR) { (response); }20) ; 22 23});
When passing with the Data property, if you are passing a key-value pair as an object, you can use the $.param () method to convert the object to a string key-value pair format.
var obj = {a:1, b:2, c:3};
var form = $.param (obj);
alert (form);
Note: Using $.param () to convert key-value pairs in the form of objects to string key-value pairs of URL addresses, you can pass the form content more stably and accurately. Because sometimes the program has limited ability to parse complex serialization, it is prudent to pass the Obj object directly.
Original http://www.cnblogs.com/ttcc/p/3802639.html