Use jQuery to simplify Ajax Development

Source: Internet
Author: User

Learn the basic principles of jQuery, explore its features and functions, execute some common Ajax tasks, and learn how to use plug-ins to expand jQuery.
What is jQuery?
JQuery was created by John Resig in early 2006. It is a very useful JavaScript library for any programmer who uses JavaScript code. Whether you are new to the JavaScript language and want to obtain a library that can solve some complex problems in Document Object Model (DOM) scripts and Ajax development, jQuery is your first choice as a senior JavaScript expert tired of DOM scripts and boring repetitive work in Ajax development.
JQuery helps you ensure that the Code is concise and easy to read. You no longer have to write a bunch of repeated loop code and DOM script library calls. With jQuery, You can grasp the key points of the problem and use as few code as possible to implement the functions you want.
There is no doubt that jQuery's principle is unique: its purpose is to ensure that the Code is concise and reusable. After understanding and understanding this principle, you can start to learn this tutorial and see how many improvements jQuery has made to our programming methods.
Simplified code
The following is a simple example to illustrate the impact of jQuery on code. To execute some really simple and common tasks, for example, attaching a click event to each link in a certain area of the page, you can use pure JavaScript code and DOM scripts, as shown in Listing 1.
Listing 1. The jQuery DOM script is not used Copy codeThe Code is as follows: var external_links = document. getElementById ('external _ links ');
Var links = external_links.getElementsByTagName ('A ');
For (var I = 0; I <links. length; I ++ ){
Var link = links. item (I );
Link. onclick = function (){
Return confirm ('you are going to visit: '+ this. href );
};
}

Listing 2 shows the same functions implemented using jQuery.
Listing 2. Using the jQuery DOM scriptCopy codeThe Code is as follows: $ ('# external_links A'). click (function (){
Return confirm ('you are going to visit: '+ this. href );
});

Is it amazing? With jQuery, You can grasp the key points of the problem and only let the code implement the functions you want, saving some tedious processes. You do not need to cycle the elements. The click () function completes these operations. You do not need to call multiple DOM scripts. You only need to use a short string to define the required elements.
Understanding how this code works may be a little complicated. First, we use the $ () function, the most powerful function in jQuery. We usually use this function to select elements from the document. In this example, a string containing some Cascading Style Sheet (CSS) syntax is passed to the function, and jQuery finds these elements as efficiently as possible.
If you have basic knowledge about CSS selectors, you should be familiar with these syntaxes. In Listing 2, # external_links is used to retrieve the element whose id is external_links. The space after a indicates that jQuery needs to retrieve all <a> elements in the external_links element. It is very difficult to say in English, even in DOM scripts, but in CSS, this is no more simple.
The $ () function returns a jQuery object containing all elements that match the CSS selector. JQuery objects are similar to arrays, but they come with a large number of special jQuery functions. For example, you can call the click function to specify the click handler to all elements in the jQuery object.
You can also pass an element or an element array to the $ () function, which encapsulates these elements in a jQuery object. You may want to use this function to use jQuery functions for some objects, such as window objects. For example, we usually allocate a function to a loading event as follows:
Window. onload = function (){
// Do this stuff when the page is done loading
};

Code with the same functions written using jQuery:
$ (Window). load (function (){
// Run this when the whole page has been downloaded
});

You may be aware that the process of waiting for window loading is very slow and painful, because it is necessary to wait until the entire page loads all the content, including all the images on the page. Sometimes you want to load images first, but in most cases, you only need to load Hypertext Markup Language (HTML. By creating a special ready event in the document, jQuery solves this problem by using the following methods:
$ (Document). ready (function (){
// Do this stuff when the HTML is all ready
});

This Code creates a jQuery object around the document element and creates a function to call the instance when the html dom document is ready. You can call this function as needed. In addition, you can use shortcuts to call this function in the real jQuery format. This is simple. You only need to pass a function to the $ () function:
$ (Function (){
// Run this when the HTML is done downloading
});

So far, I have introduced three usage methods of the $ () function. The fourth method can use strings to create elements. A jQuery object containing the element is generated. The example shown in listing 3 adds a section to the page.
Listing 3. Creating and attaching a simple Section
$ ('<P> </p> ')
. Html ('Hey World! ')
. Css ('background', 'yellow ')
. AppendTo ("body ");

In the previous example, you may have noticed that another powerful feature of jQuery is method chaining ). Each time you call a method on a jQuery object, the same jQuery object is returned for the method. This means that if you need to call multiple methods for the jQuery object, you do not have to re-type the selector to achieve this purpose:
Certificate ('your message'0000.css ('background ', 'yellow'0000.html ('Hello! '). Show ();

Making Ajax simple
Using jQuery makes Ajax easier. JQuery provides some functions to make simple work easier and complex work no longer complicated.
The most common use of Ajax is to load an HTML code to a certain area of the page. To do this, simply select the required elements and use the load () function. The following is an example of updating statistics:
('{Stats'{.load('stats.html ');

Generally, we only need to pass some parameters to a page on the server. As you expected, using jQuery is very simple. You can use $. post () or $. get (), which is determined by the required method. If necessary, you can also pass an optional data object and callback function. Listing 4 shows a simple example of sending data and using callback.
Listing 4. Use Ajax to send data to the page
$. Post ('Save. cgi ',{
Text: 'My string ',
Number: 23
}, Function (){
Alert ('your data has been saved .');
});

If you really need to write some complex Ajax scripts, you need to use the $. ajax () function. You can specify xml, script, html, or json. jQuery automatically prepares suitable results for the callback function, so that you can use the results immediately. You can also specify beforeSend, error, success, or complete callback functions to provide users with more feedback on the Ajax experience. In addition, some other parameters are available. You can use them to set the Ajax request timeout, or set the "last modification" status on the page. Listing 5 shows an example of retrieving an XML document using some of the parameters I mentioned.
Listing 5. $. ajax () makes Ajax complex and simple
$. Ajax ({
Url: 'document. xml ',
Type: 'get ',
DataType: 'xml ',
Timeout: 1000,
Error: function (){
Alert ('error loading XML document ');
},
Success: function (xml ){
// Do something with xml
}
});

After the success callback function returns an XML document, you can use jQuery to retrieve this XML document in the same way as retrieving HTML documents. This makes it quite easy to process XML documents and integrates content and data into your Web site. Listing 6 shows an extension of the success function, which adds a list item to the Web page for each <item> element in XML.
Listing 6. Using jQuery to process XML documents
Success: function (xml ){
$ (Xml). find ('item'). each (function (){
Var item_text = $ (this). text ();
$ ('<Li> </li> ')
. Html (item_text)
. AppendTo ('ol ');
});
}

Add an animation to HTML
You can use jQuery to process basic animations and display effects. The animation () function is the core of the animation Code. It is used to change any numeric CSS style values that change over time. For example, you can change the height, width, opacity, and position. You can also specify the animation speed as millisecond or predefined speed: slow, medium or fast.
The following is an example of changing the height and width of an element at the same time. Note that these parameters have no starting values, but only the final values. The start value is taken from the current size of the element. I also attached a callback function.
$ ('# Grow'). animate ({height: 500, width: 500}, "slow", function (){
Alert ('the element is done growing! ');
});

JQuery's built-in functions make it easier to complete more common animations. You can use show () and hide () elements to display them immediately or at a specific speed. You can also use fadeIn () and fadeOut (), or slideDown () and slideUp () to display and hide elements, depending on the display effect you need. The following example defines a sliding navigation menu.
$ ('# Nav'). slideDown ('low ');

DOM script and Event Processing
Perhaps jQuery is best at simplifying DOM scripts and event processing. It is very simple to traverse and process the DOM, and it is also very easy to append, remove and call events, and it is not as error-prone as manual operations.
In essence, jQuery makes common operations in DOM scripts easier. You can create elements and use the append () function to link them with other elements. clone () is used to copy elements, html () is used to set content, and empty () is used () delete the content of the function. Use the remove () function to delete all elements. Even if you use the wrap () function, wrap these elements with other elements.
By traversing the DOM, some functions can be used to change the content of the jQuery object itself. You can obtain all the siblings (), parents (), and children () of the element (). You can also select the next () and prev () sibling elements. The find () function is perhaps the most powerful function. It allows you to use the jQuery selector to search for descendant elements in jQuery objects.
If you use end () functions in combination, these functions become more powerful. This function is similar to the undo function and is used to return the jQuery object before calling the find () or parents () function (or other traversal functions.
If you use the method chaining together, these functions can make complex operations very simple. Listing 7 shows an example with a logon form and related elements.
Listing 7. Easily traverse and process the DOM
$ ('Form # login ')
// Hide all the labels inside the form with the 'optional' class
. Find ('label. optional'). hide (). end ()
// Add a red border to any password fields in the form
. Find ('input: password'0000.css ('border', '1px solid red'). end ()
// Add a submit handler to the form
. Submit (function (){
Return confirm ('Are you sure you want to submit? ');
});

Whether you believe it or not, this example is just a line of code with blank links. First, select the logon form. Then, it is found that there are optional tags, hide them, and call end () to return the form. Then, I created a password field, changed its border to red, and called end () again to return the form. Finally, I added a submit event handler in the form. Among them, it is particularly interesting (except for its simplicity) That jQuery completely optimizes all query operations and ensures that all content is properly linked together, you do not need to perform two queries on an element.
Processing common events is as simple as calling a function (such as click (), submit (), or mouseover (), and passing an event to the processing function. You can also use bind ('eventname', function () {}) to specify a Custom Event Handler. You can use unbind ('eventname') to delete some events or use unbind () to delete all events. For a complete list of how to use these functions, see the jQuery Application programming Interface (API) Documentation in reference.

Releases the powerful energy of the jQuery selector.
We often use ID to select elements, such as # myid, or the class name, such as div. myclass, to select elements. However, jQuery provides a more complex and complete selector syntax that allows us to select almost all combinations of elements in a single selector.
JQuery's selector syntax is mainly based on CSS3 and XPath. The more you know about CSS3 and XPath, the more convenient it is to use jQuery.
CSS3 contains some syntaxes not supported by all browsers, So we seldom use them. However, we can still use CSS3 Selection Elements in jQuery, because jQuery has its own custom selector engine. For example, to add a horizontal bar to each empty column in the table, you can use the: empty pseudo selector ):
$ ('Td: empty'hangzhou.html ('-');

What if we need to find all the elements that do not include specific classes? CSS3 also provides a syntax to accomplish this purpose, using the: not pseudo selector: the following code shows how to hide all input content without the required class:
$ ('Input: not (. required) '). hide ();

As in CSS, you can use commas to connect multiple selectors into one. The following is a simple example of hiding all types of lists on the page at the same time:
$ ('Ul, ol, dl '). hide ();

XPath is a powerful syntax used to search for elements in a document. It is slightly different from CSS, but it can implement more functions than CSS. To add a border to the parent element of all check boxes, use the/. Syntax of XPath:
$ ("Input: checkbox/.." ).css ('border', '1px solid #777 ');

Some selectors that are not included in CSS and XPath are also added to jQuery. For example, to make a table more readable, you can usually add a different class name to the odd or even rows of the table-also known as table segmentation ). This can be done with jQuery without any effort, thanks to the odd pseudo selector. The following example uses the striped class to change the background color of all odd rows in the table:
$ ('Table. striped> tr: odd'hangzhou.css ('background', '#999999 ');

We can see how the powerful jQuery selector simplifies the code. No matter what elements you want to deal with, whether specific or fuzzy, you may find a way to define them using a jQuery selector.

Extension of jQuery using plug-ins
Unlike most software, using a complex API to compile plug-ins for jQuery is not very difficult. In fact, jQuery plug-ins are very easy to write, and you even want to write some plug-ins to make the code simpler. Below are the most basic jQuery plug-ins that can be written:
$. Fn. donothing = function (){
Return this;
};

Although very simple, you still need to explain this plug-in. First, if you want to add a function for each jQuery object, you must assign this function to $. fn. Second, this function must return a this (jQuery object) so as not to interrupt the method chaining ).
You can easily build on this example. To write a plug-in that replaces the background color with css ('background'), you can use the following code:
$. Fn. background = function (bg ){
Return this.css ('background', bg );
};
Note that you can only return values from css () Because jQuery objects have been returned. Therefore, method chaining still works well.
I recommend that you use the jQuery plug-in when you need to repeat the work. For example, if you need to use the each () function to perform the same operation repeatedly, you can use a plug-in to complete the operation.
Because jQuery plug-ins are quite easy to write, there are hundreds of plug-ins available for you to choose from. The plug-in provided by jQuery can be used for tabulation, rounded corners, slide display, tooltip, date selector, and everything we can think.
Interfaces are the most complex and widely used plug-ins. They are an animation plug-in, it is used to process sorting, drag-and-drop functions, complex effects, and other interesting and complex User interfaces (UIS ). The interface is the same for jQuery as Scriptaculous for Prototype.
Form plug-ins are also popular and useful. You can use Ajax to easily submit forms in the background. This plug-in is used to handle some common situations: You need to intercept the submission events of a form, find all different input fields, and construct an Ajax call using these fields.
Conclusion
This section briefly describes the tasks that may be completed using jQuery. JQuery is very interesting to use, so we can always learn new techniques and features that seem simple. From the moment you start using jQuery, jQuery can completely simplify your JavaScript and Ajax programming. Every time you learn a little new knowledge, your code will be simpler.
After learning jQuery, I had a lot of fun programming in JavaScript. I don't have to worry about all the boring content. I can focus on writing interesting content. After using jQuery, I almost said goodbye to the era of writing for loop code. Even when you want to use other JavaScript libraries, you can't help but get stuck. JQuery has indeed changed my views on JavaScript programming.

Related Article

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.