Simplify Ajax development using jQuery

jQuery is a JavaScript library that helps simplify the JavaScript ™ and Asynchronous JavaScript + XML (Ajax) programming. Different and similar JavaScript libraries, jQuery has a unique principle, can be succinctly expressed the common complex code. Learning jQuery Basic principles, explore its features and functions, perform some common Ajax tasks, and learn how to use plug-ins extend jQuery.
What is jQuery?

jQuery John Resig created by the early 2006, for any programmer to use JavaScript code, it is a very useful JavaScript libraries. Whether you are new to JavaScript language and would like to get a document object model to resolve (Document Object Model, DOM) scripting and Ajax development issues in the library complex, or as a DOM scripting and Ajax are tired of boring repetition of development work experts, senior JavaScript, jQuery will be your first choice.

jQuery can help you ensure that the code simple and readable. You no longer need to write code and the cycle repeated piles DOM scripting library calls. Use jQuery, you can grasp the crux of the matter, and use the code at least as far as possible to achieve your desired functionality.

There is no doubt, jQuery is a unique principle: its purpose is to ensure that the code simple and can be reused. When you understand and appreciate this principle, they can start the tutorial, and take a look at our programming jQuery number of ways to improve it.

Some simple code to simplify

Here is a simple example, it illustrates the impact of jQuery code. To perform some really simple and common task for example Yuewei page of Mouyi area of Meige link to attach a click (click) Shi Jian, You can use pure JavaScript and DOM Jiaoben Lai Dai Ma realized, as shown in Listing 1.

Listing 1. Do not use jQuery for DOM scripting

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 use of jQuery to achieve the same functionality.

Listing 2. Use jQuery's DOM Scripting

$ ('# External_links a'). Click (function () (
return confirm ('You are going to visit:' + this.href);

Is not it amazing? Use jQuery, you can grasp the crux of the matter, only to realize you want the function code, while eliminating the cumbersome process. Cycle of the elements do not, click () function will complete these operations. Similarly, the script does not need to call more than DOM. You only need to use a short string to define the required elements can be.

Understand the working principle of this code may be a bit complicated. First, we use the $ () function - jQuery the most powerful function. Usually, we are using this function to select elements from the document. In this case, a cascading style sheet that contains some (Cascading Style Sheet, CSS) syntax of the string is passed to the function, then jQuery as efficiently as possible to find out these elements.

If you have a basic knowledge of CSS selectors, you should be familiar with the syntax. In the list of 2, # external_links used to retrieve the id for the external_links elements. jQuery after a space that needs to retrieve all the elements external_links> a <element. English speaking is very convoluted, even in the DOM the script the same way, but in the CSS of this could not be easier

$ () Function returns a CSS selector that contains all the elements of the jQuery object matching. jQuery object similar to the array, but it comes with a large number of special jQuery functions. For example, you can click by calling the click function to assign function to all elements in the jQuery object.

Also to $ () function is passed an element or an element of the array, the function will package these elements in a jQuery object. You may want to use this feature jQuery function for some object, for example, window object. For example, we usually like this to the function assigned to the load event:

window.onload = function () (
/ / Do this stuff when the page is done loading

Prepared using the same functionality as jQuery code:

$ (Window). Load (function () (
/ / Run this when the whole page has been downloaded

You may have experience, waiting for the window loading process is very slow and painful because the entire page to load, etc. complete all content, including all of the pictures on the page. Sometimes, you want to complete the picture loaded, but in most cases, you only need to load the hypertext markup language (Hypertext Markup Language, HTML) on it. Through the document ready to create a special event, jQuery to solve this problem as follows:

$ (Document). Ready (function () (
/ / Do this stuff when the HTML is all ready

The code around the document element to create a jQuery object, then create a function in the HTML DOM document is ready for when the call instance. Can be arbitrarily to call this function. And the ability to truly jQuery format, use the shortcut to call this function. It's very simple, just to the $ () function passing a function on it:

$ (Function () (
/ / Run this when the HTML is done downloading

That currently only, I have to tell you about the $ () function of the three usage. The fourth method can be used to create a string element. The results will produce a jQuery object containing the element. Listing 3 shows an example of the page to add a paragraph.

Listing 3. To create and add a simple paragraph

$ ('<p> </ P>')
. Html ('Hey World!')
. Css ('background', 'yellow')
. AppendTo ("body");

In the previous example you may have noticed, jQuery to another powerful feature is the way links (method chaining). Each of the jQuery object method calls, method will return the same jQuery object. This means that if you need to call multiple methods on the jQuery object, so you do not need to re-type selector can be achieved:

$ ('# Message'). Css ('background', 'yellow'). Html ('Hello!'). Show ();

To make Ajax easy

Ajax using jQuery will become extremely simple. jQuery provides a number of functions, can make simple tasks easier, complex work has become no longer complex.

The most common use of Ajax is to load a piece of HTML code to the page of a region to go. To do this, simply select the desired element, then use the load () function can be. Here is an example of statistical information for the update:

$ ('# Stats'). Load ('stats.html');

Usually, we simply pass some parameters to the server in a page. As you would expect, using jQuery to achieve this operation are very simple. You can use the $. Post () or $. Get (), this decision by the required method. If necessary, you can also pass an optional data object and the callback function. Listing 4 shows a callback to send data and use a simple example.

Listing 4. To 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 scripting, you need to use $. Ajax () function. You can specify the xml, script, html or json, jQuery will automatically prepare the appropriate callback function results, so you can immediately use the results. You can also specify beforeSend, error, success, or complete the callback function, to provide more information on Ajax experience feedback. In addition, there are other parameters available, you can use them to set Ajax request timeout, you can set the page, "last modified" state. Listing 5 shows a use of some of the parameters I mentioned an example of retrieving XML documents.

Listing 5. $. Ajax () to make complex changes from the simple Ajax

$. 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 XML document, you can use jQuery retrieve the XML documents, HTML documents and retrieval of their way is the same. This makes handling XML documents becomes relatively easy, and the content and data into the inside of your Web site. Listing 6 shows the success of an extension function, it is XML, each element added to a list of items to the Web page.

Listing 6. Using jQuery processing XML documents

success: function (xml) (
$ (Xml). Find ('item'). Each (function () (
var item_text = $ (this). text ();

$ ('<li> </ Li>')
. Html (item_text)
. AppendTo ('ol');

Add animation to HTML

You can use jQuery to handle basic animation and display. animate () function is the core of animation code, which changes over time for changing the value of any type of CSS style value. For example, you can change height, width, opacity and location. You can also specify the speed of animation, as milliseconds or predefined speed: slow, medium or fast.

Here is a the same time change the height and width of an element in the sample. Please note that the value of these parameters have not started, only the final value. Start value from the current element size. I also attached a callback function.

$ ('# Grow'). Animate ((height: 500, width: 500), "slow", function () (
alert ('The element is done growing!');

jQuery's built-in function so that more easier to complete common animation. You can use show () and hide () elements appear immediately or display a specific rate. You can also use the fadeIn () and fadeOut (), or slideDown () and slideUp () to display and hide the element, depending on the display you need. The following example defines a down navigation menu.

$ ('# Nav'). SlideDown ('slow');

DOM scripting and event handling

JQuery is perhaps the best at simplifying DOM scripting and event handling. DOM traversal and processing is very simple at the same time add, remove and invoke event is also very easy, and not as easy manual operation error.

In essence, jQuery DOM script can make common operations easier. You can create elements and use the append () function to their links with some other elements together, using the clone () copy elements, using html () set the content, use empty () function to delete the content, use the remove () function to delete all elements, even using the wrap () function, these elements with other elements packaged together.

By traversing the DOM, a number of functions can be used to change the contents of the jQuery object itself. Access to all elements of siblings (), parents () and children (). You can also select the next () and prev () brother element. find () function is perhaps the most powerful function, which allows the use of jQuery selectors Search jQuery object descendants of the element element.

If the combined end () function, then these functions will become even stronger. This function is similar to undo function, calling for the return to the find () or parents () function (or other traversal function) before the jQuery object.

If the link with the method (method chaining) used together, these functions can make the complex seem very simple operation. Listing 7 shows an example that contains a login form and deal with some of the elements.

Listing 7. Easy to 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', '1 px solid red '). End ()

/ / Add a submit handler to the form
. Submit (function () (
return confirm ('Are you sure you want to submit?');

No matter whether you believe that this example is a line blank to be filled with links to the code. First, select the login form. Then found that it contained an optional tag, hide them, and call end () return the form. Then, I created a password field, its borders into the red, again calling end () return the form. Finally, I added a submit form event handler. One particularly interesting is that (in addition to its simplicity beyond), jQuery fully optimize all the query operation, to ensure that all elements are linked together well after the implementation of an element does not require two queries.

Deal with common events like calling function (for example, click (), submit () or mouseover ()) and its as simple as passing the event handler. In addition, you can use the bind ('eventname', function (){}) specify a custom event handler. You can use unbind ('eventname') to delete some of the events or use unbind () to delete all the events. To use these functions a complete list, see the references in the jQuery application programming interface (Application Program Interface, API) documentation.

The release of the powerful energy of jQuery selectors

We often use the ID to select elements, such as # myid, or by class name, such as div.myclass to select elements. However, jQuery provides a more complex and complete selector syntax that allows us to select a single selector combination of almost all of the elements.

jQuery's selector syntax is based mainly on CSS3 and XPath in. On CSS3 and XPath to know more, add more handy when using jQuery. The complete list of jQuery selectors, including CSS and XPath, see Resources for links.

CSS3 contains some not all browsers support the syntax, so we seldom use it. However, we can still use the CSS3 select jQuery elements, because jQuery has its own custom selector engine. For example, to an empty table for each column are added a dash, you can use:: empty pseudo-selector (pseudo-selector):

$ ('Td: empty'). Html ('-');

If you need to find out all the non-specific category of elements? CSS3 also provides a syntax to accomplish this purpose, use the: not pseudo-selector: the following code shows how to hide all non-required classes of input:

$ ('Input: not (. Required)'). Hide ();

And the CSS in the same number of options you can use a comma to connect into one. Here is a hidden page also lists all types of simple example:

$ ('Ul, ol, dl'). Hide ();

XPath is a powerful syntax, the search for elements in the document. It is slightly different with the CSS, but it can realize the function of slightly more than CSS. All the check boxes in the parent element to add a border, you can use XPath's / .. syntax:

$ ("Input: checkbox /.."). css ('border', '1 px solid # 777 ');

jQuery also added some CSS and XPath is not the selector. For example, to make a table more readable, usually in the form of the odd line or even line attached to a different class name - also known as the table section (striping). Can be done effortlessly using jQuery, which required thanks to odd pseudo-selector. The following example uses the striped class change form all the odd lines of the background color:

$ ('Table.striped> tr: odd'). Css ('background', '# 999999');

We can see the powerful jQuery selectors is to simplify the code. Whether you want to deal with what kind of elements, regardless of whether the element is a specific thing is vague, are likely to find a way to use a jQuery selection device on Tamenjinxing Ding Yi.

Use plug-ins extend jQuery

And most of the software is different from using a complex API for the jQuery plugin is not very difficult to write. In fact, jQuery plug-in is very easy to write, you can even hope to write some plug-ins to make the code easier. The following can be written in the most basic jQuery plug-ins:

$. Fn.donothing = function () (
return this;

Although very simple, but still need some explanation on this plugin. First, if a jQuery object for each add a function, the function must be assigned to the $. Fn. Second, this function must return a this (jQuery object) so as not to interrupt the method link (method chaining).

Can easily build on this example. To change the background color to write a plugin to replace the use of css ('background'), you can use the following code:

$. Fn.background = function (bg) (
return this.css ('background', bg);

Qing Note that you can only from the css () to return value, since it has been returned to the jQuery object. Therefore, the method link (method chaining) is still working well.

I suggest that when the need to repeat the work using the jQuery plug-in. For example, if you need to use each () function repeatedly perform the same operation, you can use a plug to complete.

Because jQuery plug-in very easy to prepare, so there are hundreds of options available for your use. jQuery plug-ins available for tabulation, rounded corners, slide shows, tools, tips, date selectors, and all the results we can think of. A complete list of the plug-in, see Resources.

The most complex and most widely used plug-in to an interface (Interface), it is a Flash plug-in for processing sorting, drag and drop functionality, complex effects, as well as other interesting and complex user interface (User Interface, UI). Interface for jQuery is the same as Scriptaculous for Prototype.

Form plug-in is also popular and very useful it can be passed easily in the background using Ajax to submit the form. This plug-in for handling some common situations: You need to intercept a form to submit events, find out all the different input fields and use these fields to construct a Ajax call.
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Simplify Ajax development using jQuery

  • hibernate call stored procedure

    hibernate call stored procedure

  • hibernate using c3p0 connection pooling

    Private c3p0 for open source's JDBC connection pool, with the release hibernate. This article describes how to use the hibernate configuration in c3p0. c3p0 connection pool configuration is v ...

  • Hibernate configuration parameters

    Hibernate in the configuration file: <properties> <property name="" value="create" /> </ properties> Parameter Description: validate load hibernate, the authentication to create a database t ...

  • Build flex + spring + blazeds + hibernate application

    Build flex + spring + blazeds + hibernate application First, set up the project blazeds 1, will blazeds.war extract to a directory, such as: myflex /; 2, set up java works were such as: MyFlex, in the orientation of selection create project from exis ...

  • Hibernate connection pool configuration

    Hibernate connection pool configuration <! - Jdbc -> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </ property> <property name="connection.url"> jdbc: oracle: thin: @

  • hibernate to use the principle of

    The use of hibernate, implementation of data persistence. Has the following several processes. One configuration database connection information. Hibernate.config 2 configuration mapping. 3 use: the use of the process are the following steps: 3.1: Ge ...

  • hibernate generic generic DAO

    package org.lzpeng.dao; import; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *

  • Struts2 + hibernate + spring problem user log in

    dao layer services layer action jsp <tr> <td align="center"> <b> user name: </ b> </ td> <td> <s: textfield name = "czyNumber" cssClass = "textstyle" theme = "simple" size = &q

  • Hibernate secondary cache

    Hibernate cache: 2-bit cache, also known as process-level cache or SessionFactory level cache, secondary cache can be shared by all of the session Cache configuration and the use of: Will echcache.xml (the document code in hibernate package directory ...

  • Hibernate's lazy strategy

    hibernate Lazy strategy can be used in: <class> tag, it can be true / false Tags can <PROPERTY> values true / false type of necessary tools to enhance <set> <list> can tag values true / false / extra <many-to-one> <on ...

blog comments powered by Disqus
Recent Entries
Tag Cloud
Random Entries