While studying the "sharp jquery Sixth" jquery and Ajax applications, now take the following notes:
Let's take a look at what is Ajax? Ajax is all called "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML), which does not refer to a single technology, but rather organically leverages a series of interactive Web application-related technologies to form a combination. Briefly, without overloading the entire page, Ajax loads the data in the background and displays it on the Web page.
Let's take a brief look at Ajax. As early as 1998, Microsoft introduced an ActiveX control that was able to execute asynchronous requests under script control. In 2005, Adaptive Pathde Jesse James Garrett created the term Ajax (asynchronous JavaScript and XML, asynchronous JavaScript and XML)
The life cycle of an AJAX request is to send a request from the client to the server and back again from the server side. Before the server makes a request, you need to perform the following setup steps:
() Specify HTTP methods, such as (post or get);
Provide the URL of the server-side resource to be contacted;
Tell the XHR instance how to communicate the progress;
Provide any principal content for the POST request.
Advantages and disadvantages of 6.1Ajax
Its advantages are: 1. Plug-in support is not required: Ajax does not require any browser plug-ins, it can be supported by most mainstream browsers, users only need to allow JS to execute on the browser.
2. Excellent user experience: This is also the biggest advantage of Ajax technology, can update the data without refreshing the whole page, so that the Web application can respond to the user's actions more quickly.
3. Improve the performance of Web programs: The biggest difference in performance between Ajax mode and traditional mode is the way in which data is transferred, in traditional mode, data submission is implemented by forms (form), and data acquisition is retrieved by full page refresh to retrieve the whole page content. That is, Ajax submits data asynchronously to a server, instead of using the legacy "commit-to-process-Reload page" (post-process-reload) technology, Ajax mode simply submits the data that you want to submit to the server by XMLHttpRequest the object, which is sent on demand.
4. Offload server and bandwidth: Ajax works by adding a middle tier between the user and the server, making the user operation asynchronous with the server response. It creates an AJAX engine on the client side, transferring the workload of some servers in the traditional way to the client, making it easier for client resources to handle and reduce the burden on the server and bandwidth.
Ajax has the following shortcomings:
1. The browser has insufficient support for XMLHttpRequest objects. One of the shortcomings of Ajax comes first from the browser.
2. Damage the browser forward, "Back" button normal function. The function of the "forward" and "Back" buttons in Ajax is invalidated, although it is possible to use the "forward" and "back" buttons with a certain method (adding anchor points), but it is a lot more troublesome than the traditional way.
3. Lack of support for search engines
4. Lack of development and commissioning tools
XMLHttpRequest Object of 6.2Ajax
The core of Ajax is the XMLHttpRequest object, which is the key to the AJAX implementation-sending an asynchronous request, receiving the corresponding and executing the callback is done through it.
6.3 Installing the Web Environment--appserv
The installation of the article is Appserv, my own computer is using Nginx
6.4 Writing the first Ajax example
The main explanation is an AJAX example implemented with traditional JavaScript.
Ajax in 6.5jQuery
In jquery, jquery encapsulates Ajax operations and provides several AJAX-related methods. With these methods, you can use HTTP GET and HTTP POST to request text from a remote server, html,xml or json-and we can load these external data directly into the selected elements of the Web page.
The $.ajax () method in jquery is the lowest-level method, and the 2nd layer is the load (), $.get (), and $.post () methods, and the third layer is the $.getscript () and $.getjson () methods.
6.5.1
JQuery $.load () method
Structure: Load (Url[,data][,callback])
Here is a jquery code for an example of the load () method:
$ (function () {$ ("#btn1"). Click (function () {$ ("#test"). Load ("here.html");})
Note: In the load () method, the callback function (callback) is triggered whenever the request completes (complete), regardless of whether the AJAX request is successful.
JQuery $.get () method
The $.get () method uses an HTTP get method to make an asynchronous request
Structure: $.get (Url[,data][,callback][,type])
The following example uses the $.get () method to retrieve data from a file on the server:
$ (function () {$.get (' test.txt ', function (data,status) {alert ("Data:" +data+ "\ n Status:" +status);});//$.get () The first parameter is the URL we want to request. The second parameter is a callback function. The first callback parameter contains the contents of the requested page, and the second callback parameter holds the requested State. The callback function is not called until the data is successfully returned (success), which is not the same as the load () method. })
$.post () method
It has the same structure and usage as the $.get () method, but there are still the following differences between them:
JQuery $.post () method
The $.post () method requests data from the server via an HTTP POST request
Grammar:
$.post (Url,data,callback);
Because all data submitted by post and get is available through $_request[], you can switch between a GET request and a POST request simply by changing the jquery function.
In addition, when the load () method is passed with a parameter, the request is sent using the Post method. You can also use the load () method to accomplish the same function.
But during this time error, and then found the reason: Apache, IIS, Nginx and so on most Web servers, do not allow static files to respond to post requests, information found online: http://blog.csdn.net/haitun312366/article /DETAILS/8241350, it seems that you need to modify the relevant configuration Nginx.
6.5.3$.getscript () method and $.getjson () method
1.$.getscript () method
Sometimes it is completely unnecessary to get all the JavaScript files you need when the page is first loaded. Although you can re-use which JavaScript file, create <script> tags dynamically, such as:
$ (document.createelement ("script")). attr ("src", "test.js"). AppendTo ("Head");
Or:
$ ("<script type= ' text/javascript ' src= ' test.js '/>"). AppendTo ("Head" >;
But this approach is not ideal. To do this, jquery provides the $.getsctipt () method to directly load the. js file, which is as easy as loading an HTML fragment, and does not require a JavaScript file to be processed, and the JavaScript file is automatically executed. The jquery code is as follows:
$ (function () {$ ("#send"). Click (function () {$.getscript (' test.js ');})})
This method also has a callback function.
2.$.getjson () method
The $.getjson () method is used to load the JSON file in the same way as the $.getscript () method.
$ (function () {$ (' #send '). Click (Function (event) {$.getjson (' Test.json ', function (data) {//data: Returned)})})
6.5.4 $.ajax () method
The $.ajax () method is the lowest-level AJAX implementation
Structure: $.ajax (options)
The method has only one parameter, but in this object contains information such as the request settings and callback functions required by the $.ajax () method, the parameters are in the form of Key/value, and all parameters are optional.
The previously used $.load (), $.get (), $.post (). $.getscript and $.getjson () These methods are based on the $.ajax () method, and the $.ajax () method is the lowest AJAX implementation of jquery, It can therefore be used instead of all previous methods.
Here is an example of a simple Ajax request:
$ (function () {$.ajax ({url: "here.html", DataType: "HTML", Success:function (R) {Console.log ("make it");},error: Function (r) {Console.log ("something didn ' t work");})})
If you want to make an AJAX request unaffected by the global method, you can set the global in the parameter to False when using the $.ajax (options) method
Set the request default value
When we plan to launch a large number of requests, it is convenient to set default values for these options on the page. jquery provides a way for us to define a set of default Ajax property values, which are used if the values of those properties are not overridden. This simplifies the page if you want to initiate many similar AJAX requests.
$.ajaxsetup (Options)
Creates a passed set of option properties as the default value for subsequent calls to $.ajax (). Parameter options: An object instance whose properties define a set of default Ajax options.
Note: The default values set by this function are not applied to the load () method. For utility functions such as $.get () and $.post, these default values do not override the HTTP method. For example, setting the default type to get does not cause $.post () to use the Get method of HTTP.
Suppose you want to create a page that guards most AJAX requests (created using utility functions instead of the load () method), we want to set some default values so that they are not specified each time they are called. We can write this code on the first line of the <script> element in the header of the page
$.ajaxsetup ({type: ' POST ', Timeout:5000,datatype: ' HTML '});
This will ensure that each subsequent Ajax call (except for the load () method mentioned previously) will use these default values. Unless you use incoming Ajax to use the properties of the function to overwrite them with the display.
6.7 Ajax global Events in jquery
Here's a look at the AJAX global events in jquery. 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 the Ajaxstop () method is triggered when the AJAX request ends. These methods are global in that they are triggered whenever an AJAX () request occurs, regardless of where the code that created them is located.
$ (function () {$ ("#loading"). Ajaxstart (function () {$ (this). Show ();}); $ ("#loading"). Ajaxstop (function () {$ (this). Hide ();}); $.get (' Test.txt ', function (data,status) {alert ("Data:" +data+ "\ n Status:" +status);//Console.log (123);}); })
In addition to Ajaxstart () and Ajaxstop (), there are several other methods:
During the period about Ajaxsend () encountered some problems, recorded:
$ (document). Ready (function () {
$ ("#div1"). Ajaxsend (function () {
alert (123);
});
$ (" Button "). Click (function () {
$ ("#div1"). Load ("here.html");
});
}); /above defines $ ("#div1"). Ajaxsend (function () {}); The event is not in any of the onclick events. If a duplicate definition of a global event occurs, the global event $ ("#div1") is defined once in this example, in each onclick event. Ajaxsend (function () {}); Then, the global event increases the number of executions rather than overriding the previous definition
It was found here. Related information: http://zhina123.blog.163.com/blog/static/41789578201211931319529/
Each event in jquery is executed in the following order:
1.ajaxStart (Global event)
2.beforeSend
3.ajaxSend (Global event)
4.success
5.ajaxSuccess (Global event)
6.error
7.ajaxError (Global event)
8.complete
9.ajaxComplete (Global event)
10.ajaxStop (Global event)
Serialization issues
In the course of the project, there will often be data transfer, in the process of transmitting data, the sender needs to convert the object into a sequence of bytes to be transmitted on the network, and the receiver needs to restore the byte sequence to an object. Serialization (serialization) is the process of transforming the state information of an object into a form that can be stored or transmitted.
jquery provides the serialize () method, which acts on a jquery object, serializing the DOM element content to a string for AJAX requests.
Format: var data = $ ("form"). Serialize ();
Function: Serializes the contents of the form into a single string.
This way, when Ajax submits the form data, it is not necessary to enumerate each parameter. Simply set the data parameter to $ ("form"). Serialize ().
$ (document). Ready (function () {
$ ("button"). Click (function () {
$ ("div"). Text ($ ("form"). Serialize ());
});
});
Because the serialize () method is used for jquery objects, it can be used not only by the form, but also by the elements selected by other selectors, such as:
$ (": Checkbox,:radio"). Serialize ();
Serializearray () method
Format: var jsondata = $ ("form"). Serializearray ();
Function: Serializes a page form into a JSON-structured object. Note that the method does not return a string, but instead serializes the DOM element, returning the data in JSON format. Also because it is an object, you can use the $.each () function to iterate over the output of the data.
For example, [{"Name": "Lihui", "Age": "20"},{...}] get data for Jsondata[0].name
$ (function () { $ ("#send"). Click (function () { var $data = $ (": Checkbox,:radio"). Serializearray (); alert ($data); }) })
$.param () method
It is the core of the Serialize () method, which is used to serialize an array or an object according to Key/value
$ (function () {var obj = {A:1,b:2,c:3};var k = $.param (obj); alert (k);}) Output a=1&b=2&c=3
Avoid buffering
For Ajax requests, there is a fundamental problem with data buffering in GET requests. Unfortunately, even if necessary, the server rarely re-requests data in AJAX requests. The browser simply reads the data from the local cache sink (to be aware that the browser has historically never been designed for asynchronous data requests). This problem first affects Internet Explorer. In manual programming, it is a good workaround to append a random number or timestamp generated by JavaScript after the query string, whether on the server or on the client side, where the value is largely non-functional. This method of knowledge in order to tell the browser that the data must be reloaded. In fact, this technique is the only simple and reliable way to avoid buffering behavior (a behavior that is really useful in traditional Web data requests). The framework that explicitly provides such mechanisms (such as Yui) is what is done in the background. In jquery, you must now manually create an additional parameter for most of the methods and append this parameter to the URL. Only the Ajax () method provides a corresponding avoidance buffer option through special parameters.
Extension technology for $.ajax ()
In jQuery1.5, 3 extended functions of $.ajax () were introduced:
Pre-Filter: Pre-filter (Prefilter) refers to the callback function executed before any AJAX request is sent and before $.ajax () handles any options
$.ajaxprefilter (function (requestoptions,originaloptions,jqxhr) {//modify Options,control the original Options,store JQXHR object etc});
Converters: Converters refer to new callback functions as well. The converter is called when the server sends response data in a data type other than expected. You can take the appropriate action in the callback function to convert the data type or introduce your own data type. The converter is saved in ajaxsetting and can be added globally.
({converters:{"text Mydatatype": function (TextValue) {if (valid (TextValue)) {if (valid (TextValue)) {//some Logicreturn Mydatatypevalue;} Else{//indicate parse-errorthrow Exceptionobject;}})
You can use converters to create custom data types (data types must be in lowercase letters).
If you look at a typical converter in the previous program manifest, you can request data of type Mydatatype, such as
$.ajax (url,{datatype: "Mydatatype"});
Dispatcher: The Dispatcher in jquery (transport) is an object that provides two methods:
Send ()
Abort ()
Both methods are used internally by $.ajax () and can be used to extend $.ajax (). However, the jquery documentation also states that the dispatcher should be used only as a last resort, when neither the pre-filter nor the converter is sufficient to affect the AJAX request.
Because each request requires its own instance of the Dispatcher object, these objects cannot be registered directly. As an alternative, you should provide a function to return such an object. The function of this generated object is called the Factory (Factory). The Distributor factory is registered as follows:
$.ajaxtransport (function (REQUESTOPTIONS,ORIGINALOPTIONS,JQXHR) {if (/*conditions for transport*/) {return {send: Function (header fields as Map,callback) {/*code for sending*/},abort:function () {/*code in case of Abort*/}}};})
This note is dominated by the "sharp jquery" (second edition), and references to "JQuery in Action" (second edition), "JQuery Application Development Practice Guide".
There are any suggestions, but also hope that everyone is not hesitate to enlighten [embrace]
Ajax Learning notes in jquery