Using jquery to simplify Ajax development _ajax related

Source: Internet
Author: User
Tags extend object model readable xpath
Learn the basics of JQuery, explore its features and capabilities, perform some common Ajax tasks, and master how to extend JQuery with Plug-ins.
What is JQuery?
JQuery was created by John Resig in early 2006 and is a useful JavaScript library for any programmer using JavaScript code. Whether you're just in touch with the JavaScript language, and want to get a library that solves some of the complex problems in the Document Object Model (model,dom) script and Ajax development, or as a tired DOM script and Ajax JQuery will be your first choice as a veteran JavaScript expert in the tedious repetitive work of development.
JQuery can help you keep your code simple and readable. You no longer have to write large stacks of repetitive loops and DOM script library calls. With JQuery, you can grasp the main points of the problem and implement the functionality you want with the least amount of code possible.
There is no doubt that the principle of jQuery is unique: Its purpose is to ensure that the code is concise and reusable. Once you understand this principle, you can start learning this tutorial and see how much jQuery has improved our programming style.
Some simple code simplification
The following is a simple example that illustrates the impact of JQuery on your code. To perform some really simple and common tasks, such as attaching a click event to each link in one area of a page, you can use pure JavaScript code and a DOM script, as shown in Listing 1.
Listing 1. No DOM script with JQuery
Copy Code code 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 (' Your are going to visit: ' + this.href ');
};
}

Listing 2 shows the same functionality that was implemented using JQuery.
Listing 2. DOM script with JQuery
Copy Code code as follows:

$ (' #external_links a '). Click (function () {
return confirm (' Your are going to visit: ' + this.href ');
});

Isn't it amazing? With JQuery, you can grasp the main points of the problem and just let the code implement the functionality you want, eliminating some tedious process. You do not have to loop the elements, and the Click () function completes these operations. There is also no need for multiple DOM script calls. You only need to use a short string to define the elements that you want.
Understanding how this code works can be a bit tricky. First, we used the $ () function, the most powerful function in--jquery. Typically, we use this function to select elements from a document. In this case, a string containing some cascading style sheets (cascading style sheet,css) syntax is passed to the function, and jQuery can find the elements as efficiently as possible.
If you have a basic knowledge of CSS selectors, you should be familiar with these syntaxes. In Listing 2, #external_links is used to retrieve an element with an ID of external_links. A space after a indicates that JQuery needs to retrieve all the <a> elements in the external_links element. Speaking in English is very round the mouth, even in the DOM script, but in the CSS this is simple
The $ () function returns a JQuery object that contains all the elements that match the CSS selector. The jquery object is similar to an array, but it comes with a large number of special jquery functions. For example, you can assign the click handler to all the elements in the JQuery object by calling the Click function.
You can also pass an element or an array of elements to the $ () function that encapsulates the elements in a JQuery object. You might want to use the JQuery function for some objects, such as window objects, using this feature. For example, we typically assign functions to load events as follows:
Window.onload = function () {
Do this stuff the page was done loading
};

Code with the same functionality written in JQuery:
$ (window). Load (function () {
Run this when the whole page has been downloaded
});

As you may realize, waiting for the window to load is very slow and painful, because you have to wait for the entire page to load all the content, including all the pictures on the page. Sometimes, you want to finish loading the picture first, but in most cases you just load the Hypertext Markup Language (hypertext Markup language,html). JQuery solves this problem by creating special ready events in the document, as follows:
$ (document). Ready (function () {
Do this stuff the HTML was all ready
});

This code creates a JQuery object around the document element and then builds a function to invoke the instance when the HTML DOM document is ready. You can call this function arbitrarily, as needed. And be able to call this function using shortcuts in real jQuery format. This is simple, just passing a function to the $ () function is OK:
$ (function () {
Run this when the HTML was done downloading
});

So far, I've introduced three uses of the $ () function. The fourth method can use strings to create elements. The result produces a JQuery object that contains the element. The example shown in Listing 3 adds a paragraph to the page.
Listing 3. Create and attach a simple paragraph
$ (' <p></p> ')
. html (' Hey world! ')
. css (' background ', ' yellow ')
. Appendto ("body");

As you may have noticed in the previous example, another powerful feature in JQuery is the method link (methods chaining). Each time a method is invoked on a jquery object, the method returns the same jquery object. This means that if you need to call multiple methods on a JQuery object, you do not have to retype the selector to do so:
$ (' #message '). CSS (' background ', ' yellow '). html (' hello! '). Show ();

Make Ajax Simple
Using JQuery will make Ajax as simple as it gets. JQuery provides a number of functions that make simple work easier, and complex work becomes less complex.
The most common use of Ajax is to load a piece of HTML code into an area of the page. To do this, simply select the element you want, and then use the load () function. The following is an example for updating statistics:
$ (' #stats '). Load (' stats.html ');

Typically, we simply pass some parameters to a page in the server. As you would expect, using JQuery to do this is a very simple operation. You can use $.post () or $.get (), which is determined by the method you want. You can also pass an optional data object and callback function, if needed. Listing 4 shows a simple example of sending data and using callbacks.
Listing 4. Using Ajax to send data to a page
$.post (' save.cgi ', {
Text: ' My string ',
Number:23
}, function () {
Alert (' Your data has been saved. ');
});

If you do need to write some complex Ajax scripts, you need to use the $.ajax () function. You can specify that XML, script, HTML, or json,jquery will automatically prepare the appropriate results for the callback function so that you can use the result immediately. You can also specify Beforesend, error, success, or complete callback functions to provide users with more feedback about the Ajax experience. In addition, there are other parameters available that you can use to set the timeout for the Ajax request, or to set the status of the page "last modified." Listing 5 shows an example of retrieving an XML document using some of the parameters I mentioned.
Listing 5. $.ajax () makes Ajax simpler by complexity
$.ajax ({
URL: ' Document.xml ',
Type: ' Get ',
DataType: ' xml ',
timeout:1000,
Error:function () {
Alert (' Error loading XML document ');
},
Success:function (XML) {
Do something with XML
}
});

When the success callback function returns an XML document, you can use JQuery to retrieve the XML document in the same way that it retrieves an HTML document. This makes processing XML documents quite easy, and integrates content and data into your Web site. Listing 6 shows an extension of the success function, which adds a list item to a Web page for each <item> element in the 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 animations to HTML
You can use JQuery to handle basic animations and display effects. The animate () function is the core of the animation code, which is used to change any type of CSS style value that changes over time. For example, you can change height, width, opacity, and position. You can also specify the speed of the animation, either as a millisecond or as a predefined speed: slow, medium, or fast.
Here is an example of changing the height and width of an element at the same time. Note that these parameters do not have a start value, only the final value. The start value is taken from the current dimension of the element. I also attached a callback function.
$ (' #grow '). Animate ({height:500, width:500}, "Slow", function () {
Alert (' The element is done growing! ');
});

The built-in functions of jQuery make it easier to do more common animations. You can use the show () and hide () elements to display immediately or at a specific speed. You can also display and hide elements by using fadeIn () and fadeout (), or Slidedown () and Slideup (), depending on the display effect you need. The following example defines a sliding navigation menu.
$ (' #nav '). Slidedown (' slow ');

DOM Scripting and event handling
Perhaps JQuery is best at simplifying DOM scripting and event handling. Traversing and processing the DOM is simple, while attaching, removing, and invoking events is also easy, and not as error-prone as manual operations.
In essence, jQuery can make common operations in DOM scripts easier. You can create elements and use the Append () function to link them with other elements, use Clone () to copy elements, use HTML () to set content, delete content using the empty () function, remove all elements using the Remove () function, even if you are using the Wrap () function that wraps these elements with other elements.
By traversing the DOM, some functions can be used to change the contents of the JQuery object itself. You can get 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 that allows you to use the jquery selector to search for descendant elements of elements in a jquery object.
If the end () function is used in conjunction, these functions will become more powerful. This function is similar to the Undo function, which is used to return to the JQuery object before the find () or parents () function (or other traversal function) is invoked.
If used together with method chaining, these functions can make complex operations look very simple. Listing 7 shows an example that contains a login form and handles some of the elements associated with it.
Listing 7. Easily traverse and process 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 '). CSS (' border ', ' 1px solid red '). End ()
Add a submit handler to the form
. Submit (function () {
return confirm (' Are your sure you want to submit? ');
});

Whether you believe it or not, this example is just a line of linked code that is full of blank. First, select the login form. It then discovers that it contains optional tags, hides them, and calls end () to return to the form. Then I created the password field, changed its bounds to red, and called End () again to return to the form. Finally, I added a Submit event handler to the form. What's particularly interesting is that, in addition to its simplicity, JQuery optimizes all query operations, making sure that everything is well linked, without having to perform two queries on one element.
Handling common events is as simple as calling a function (for example, click (), submit (), or mouseover ()) and passing an event handler function for it. In addition, you can use bind (' EventName ', function () {}) to specify a custom event handler. You can use Unbind (' EventName ') to delete certain events or use Unbind () to delete all events. For a complete list of how these functions are used, see the JQuery Application Programming Interface (application program INTERFACE,API) documentation in resources.

Release the powerful power of the JQuery selector
We often use IDs to select elements, such as #myid, or to select elements through class names such as Div.myclass. However, JQuery provides a more complex and complete selector syntax, allowing us to select almost all element combinations in a single selector.
JQuery's selector syntax is primarily based on CSS3 and XPath. The more you know about CSS3 and XPath, the more handy it is to use jQuery.
CSS3 contains some syntax that is not supported by all browsers, so we rarely use it. However, we can still use CSS3 to select elements in jquery because jquery has its own custom selector engine. For example, to add a horizontal bar to each empty column in a table, you can use:: Empty pseudo selector (Pseudo-selector):
$ (' Td:empty '). html ('-');

What if you need to find all elements that do not contain a particular class? CSS3 also provides a syntax to do this, using: not pseudo selector: The following code shows how to hide all input without 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 a page at the same time:
$ (' UL, OL, DL '). Hide ();

XPath is a powerful syntax for searching for elements in a document. It is slightly different from CSS, but it can achieve slightly more functionality than CSS. To add a border to the parent element of all check boxes, you can use the XPath/. Grammar:
$ ("input:checkbox/."). CSS (' border ', ' 1px solid #777 ');

JQuery also adds a few selectors that are not in CSS or XPath. For example, to make a table more readable, it is often possible to attach a different class name to the odd or even rows of a table--or to fragment a table (striping). Using jQuery effortlessly can do this, thanks to the odd pseudo selector. The following example uses the Striped class to change the background color of all the odd rows in the table:
$ (' table.striped > Tr:odd '). CSS (' background ', ' #999999 ');

We can see how the powerful jQuery selector simplifies the code. Whatever elements you want to deal with, regardless of whether the element is concrete or fuzzy, it is possible to find a way to define them using a jquery selector.

Using Plug-ins to extend JQuery
Unlike most software, using a complex API to write Plug-ins for jQuery is not very difficult. In fact, the JQuery plug-in is very easy to write, and you even want to write some plug-ins to make the code simpler. Here are some of the most basic jQuery plug-ins you can write:
$.fn.donothing = function () {
return this;
};

Although very simple, but still need to do some explanation of this plugin. First, if you want to add a function to each JQuery object, you must assign the function to $.fn. Second, this function must return a This (JQuery object) so that it does not interrupt the method link (methods chaining).
You can easily build on top of this example. To write a plugin that replaces the background color, instead of using CSS (' background '), you can use the following code:
$.fn.background = function (BG) {
return this.css (' background ', BG);
};
Note that you can return a value only from CSS () because you have already returned the JQuery object. Therefore, method chaining is still working well.
I recommend that you use the JQuery plugin when you need to repeat your work. For example, if you need to use each () function to do the same thing over and over again, you can use a plug-in to do so.
Because the JQuery plugin is fairly easy to write, there are hundreds of options you can use. JQuery provides plug-ins for tabulation, fillet, slide shows, ToolTips, date selectors, and all the effects we can think of.
The most complex, most widely used plug-in is the interface (Interface), an animated plug-in that handles sorting, drag-and-drop functionality, complex effects, and other interesting and complex user interfaces (users Interface,ui). The interface is as scriptaculous for JQuery as for Prototype.
Form Plug-ins are also popular and useful, and they allow you to easily submit forms in the background using Ajax. This plugin handles some of the most common situations: you need to intercept a form's commit event, find all the different input fields, and use these fields to construct an Ajax call.
Conclusion
Just briefly describes the tasks that can be accomplished using jQuery. JQuery is fun to use, so we can always learn new tricks and new features that look simple. From the moment you start using jquery, jquery can completely simplify your JavaScript and Ajax programming, and your code will be a little simpler each time you learn a little bit of new knowledge.
After learning JQuery, I had a lot of fun while I was programming with the JavaScript language. Without worrying about all the boring stuff, 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 think about using other JavaScript libraries, you can't help but cringe. JQuery really changes my view of 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.