[JQuery Basics] 05 jQuery, Ajax, serialization, and jqueryajax
Well, this chapter is not as watery as the previous chapter, and it is always not good to fry leftovers.
About AJAX
The so-called Ajax, full name Asynchronous JavaScript and XML. (Asynchronous JS and XML)
Simply put, you can send and retrieve data without refreshing a new page, and then update the page.
Ajax advantages
- No plug-ins required
- Excellent User Experience
- Improve the Performance of web programs
- Reduce the burden on servers and bandwidth
Ajax Deficiency
- Insufficient browser compatibility
- Destroys the normal function of the browser's forward and backward buttons
- Insufficient support for search engines
- Lack of development and debugging tools
Well, these are the shortcomings of a few years ago. The technology is developing rapidly, and these shortcomings will be gradually remedied. At least it is not difficult to debug Ajax now.
The core of Ajax is the XMLHttpRequest object, which is the key to Ajax implementation.
The traditional example of Ajax implementation is no longer mentioned. It's so painful. I don't even remember it. I 've searched a lot on the Internet.
About Ajax in jQuery
The $. ajax () method encapsulates the most primitive JavaScript Ajax method.
Load (), $. get (), $. post () is encapsulated by $. ajax ().
$. GetScript () and $. getJSON () are further encapsulated.
- Load () method
- Usage: loads remote HTML code and inserts it into the DOM. It is usually used to obtain static data files. The structure is load (url [, data] [, callback]).
- The url is the requested address.
- Data (optional) is the parameter object initiated to the server.
- Callback is a callback function. A request is called whether successful or failed.
- When loading a page, you can even add filtering to the address.
$ ("# ResDiv "). load ("test.html. myClass "); // This divcontains only elements of the myClass style on the test.html page. // a complete example $ (function () {$ (" # resDiv ") is provided "). load ("text. php ", {name:" troy ", textInfo:" hello "}, function (responseText, textStatus, XMLHttpRequest) {// responseText: Content returned by the request // textStatus: Request status: success, error, notmodiffied, and timeout // XMLHttpRequest: XMLHttpRequest object });});
- $. Get () method
- Obviously, the calling method is different. Therefore, this function is a global function of jQuery. The previous methods and load () are used to operate jQuery objects.
- The $. get () method uses the GET Method for asynchronous requests. The structure is $. get (url [, data] [, callback] [, type]).
- The first three parameters are not mentioned. The only difference is that callback is called only when the request is successful.
- The type parameter is the format of the content returned by the server, including xml, html, script, json, text, and _ default.
- Example
$ ("# Send "). click (function () $. get ("get1.php", {username: $ ("# username "). val (), content: $ ("# content "). val ()}, function (data, textStatus) {// data: returned content, which can be an XML document, JSON file, HTML clip // textStatus: Request status: success, error, notmodiffied, and timeout })})
- $. Post () method
- It is the same as the get method, but one is the get method and the other is the post method.
- $. GetScript () method
- $. GetJSON () method
- Used to load a JSON file. The usage is the same as the preceding one, but only the returned json data.
$ ('# Send '). click (function () {$. getJSON ("myurl", function (data) {var html = ""; $. each (data, function (commentIndex, comment) {html + = commentIndex + ":" + comment ['username'] + ";";}) alert (html) ;}}); // pay attention to the ecch method. It is also a global function. In the callback function, the first parameter is the member index, and the second parameter is the variable and content.
By the way, the JSONP for cross-origin access
$ ("# Send"). click (function () {$. getJSON ("http: // www. A website. com/services/getMyCmpJson? Tags = car & tagmode = any & format = json & jsoncall back =? ", Function (data) {// some operations})} // JSONP is an unofficial protocol that combines json with <script> tags, it is mainly used for cross-origin web applications.
- $. Ajax () method
- This method is the underlying Ajax Implementation of jQuery, so it is naturally more powerful and complex.
Although it only has one parameter, this parameter object contains many attributes, but is optional. All attributes are listed below:
- Url: the current page address by default. You can also manually write the request address.
- Type: The default value is GET. You can also write a POST.
- Timeout: Set the request timeout (MS)
- Data: sent data
- DataType: The expected data type returned by the server.
- BeforeSend: The function called before sending. If this function returns false, the ajax request is canceled.
Function (XMLHttpRequest) {// XMLHttpRequest is the only parameter this; // The options parameter passed when this Ajax request is called}
- Complete: after the request is complete, the call is successful or fails.
Function (XMLHttpRequest, textStatus) {// textStatus describes the successful request type this; // The options parameter passed when calling this Ajax request}
- Success: callback function after successful request
Function (data, textStatus) {// data is the data returned successfully this; // The options parameter passed when calling this Ajax request}
- Error: function called when the request fails.
Function (XMLHttpRequest, textStatus, errorThrown) {// textStatus indicates the error message, and errorThrown indicates the captured error object. Generally, only one of them contains the information this; // The options parameter passed when calling this Ajax request}
- Global: The default value is true. Indicates whether to trigger a global Ajax event.
- Serialization Element
- Serialize () method
- It can serialize the content of DOM elements into strings.
// Not only can the entire form be serialized, but also a single element can be serialized, and they are all automatically encoded $. post ("myurl", $ ("# form1 "). serialize (), function (data, textStatus) {$ ("# resText" ).html (data );})
- SerializeArray () method
- It can serialize DOM element content to JSON format
- $. Param () method
- Ajax global events in jQuery
- AjaxStart () method: triggered when an Ajax request starts.
- AjaxStop () method: triggered when the Ajax request ends
<Div id = "loading"> loading... </div> $ ("# loading "). ajaxStart (function () {$ (this ). show (); // load is displayed when the ajax request starts.}); $ ("# loading "). ajaxStop (function () {$ (this ). hide (); // hide loading when ajax ends });
- AjaxComplete (): triggered when the Ajax request is complete
- AjaxError (): triggered when an Ajax request occurs. The captured error can be passed as the last parameter.
- AjaxSend (): triggered before an Ajax request is sent.
- AjaxSuccess (): triggered when the Ajax request is successful
- If you want to prevent an Ajax request from being affected by a global event, you can set the global attribute to false in $. ajax, as mentioned earlier. Of course, before ajax requests:
$. AjaxPrefilter (function (options) {// The request options. global = true before each sending ;})
Okay, it's done. Finally, we can mention setTimeout ("doMethod ()", 4000). After 4s, execute the doMethod function.
// Function updateMsg () {$. post ("myurl", {time: timestamp}, function (xml) {// do something}); setTimeout ("updateMsg ()", 4000 );}