Simplify Ajax development with jQuery

sponsored links
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 basic principles, you can concisely express common complex code. Learning jQuery Basic principles, explore its features and functions, perform some common Ajax tasks, and learn how to use the 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 library. Whether you are new to JavaScript language and want to get a document object model can be resolved (Document Object Model, DOM) scripting and Ajax development issues in the library complex, or as a DOM scripting and Ajax tired of boring repetition of the 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 have to repeat the cycle of writing code and piles of DOM scripting library calls. Use jQuery, you can grasp the main points of the problem and use the code at least as far as possible the function you want.

There is no doubt, jQuery is 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 learning this tutorial, take a look at our programming jQuery way of how many improvements it.
Some simple code to simplify

Here is a simple example, it illustrates the impact of jQuery code. To do something really simple and common tasks, for example, a particular area of the page for each link to attach a click (click) event, you can use pure JavaScript code and DOM scripting to implement, 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 that amazing? Use jQuery, you can grasp the main points of the problem, just let the code to achieve your desired function, and eliminating the cumbersome process. Elements do not need to loop, click () function will complete these operations. Also does not require multiple DOM scripting. You only need to use a short string on the definition of the elements required to.

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, and 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 Listing 2, # external_links external_links used to retrieve the id for the element. jQuery after a space that needs to retrieve all the elements external_links <a> elements. English speaking is very convoluted, even in the DOM the script too, but in CSS, this could not be easier

$ () Function returns a CSS selector matches all elements of the jQuery object. 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 handler function to assign all the elements in the jQuery object.

Can also be the $ () function to pass an element or an array of elements, the function will encapsulate those 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 whole page to load, etc. When all of the content, including all 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. In the document by creating a special ready 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, and then create a function in the HTML DOM document is ready for when the call instance. Arbitrarily according to need 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 is passed a function on it:

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

To the current stop, I have to tell you about the $ () function of the three usage. The fourth method can use a string to create elements. The results will create 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's features is another powerful method of link (method chaining). JQuery object method is called each time, the 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 achieve this purpose:

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

Make Ajax easy

Ajax using jQuery will become its simple. jQuery to provide some functions, you can make simple tasks easier, complex work is no longer complex.

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

$ ('# 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 is 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 using a simple example.
Listing 4. Send data to the page using Ajax

$. 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 result of the callback function, so you can immediately use the results. You can also specify beforeSend, error, success, or complete the callback function, to provide users with more feedback on Ajax experience. 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 the complex become 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 to retrieve the XML documents, HTML documents and retrieval of their way is the same. This makes handling XML documents has become fairly easy, and the content and data into the inside of your Web site. Listing 6 shows the success of an extension function, which for the XML element for each <item> added a list of items to the Web page.
Listing 6. Processing XML documents using jQuery

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

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

Adding animation to HTML

You can use jQuery to handle basic animation and display. animate () function is the core of the animation code, which changes over time to change 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 the animation, set in milliseconds or predefined speed: slow, medium or fast.

Here is a change in both height and width of an element 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 functions to make the animation more often easier to complete. You can use show () and hide () elements, immediately displayed or the speed of a particular display. You can also use the fadeIn () and fadeOut (), or slideDown () and slideUp () show and hide elements, depending on the display you need. The following example defines a decline in the 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, but add, remove, and calling the event is also very easy, and not as error-prone manual operations.

In essence, jQuery DOM script can make common operations easier. You can create elements and use the append () function, some of them with the other elements linked together, using the clone () to copy the 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 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 jQuery object to search for selected descendant elements.

If the combination of end () function, then these functions will become more powerful. This function is similar to the undo function, used to return to the calling find () or parents () function (or other traversal function) before the jQuery object.

If the link with the method (method chaining) used, these functions can make the complex seem very simple operation. Listing 7 shows an example that contains a login form and process relating to a number of 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?');
});

Regardless of whether you believe that this example is a blank line is full of links to the code. First, select the login form. Then found to contain an optional label, hide them, and call end () return the form. Then I created a password field, its border turns red, another call to end () return the form. Finally, I added a form to submit event handler. One particularly interesting is that (in addition to its simplicity outside), jQuery fully optimize all the queries to ensure that all content linked together well after the implementation of an element does not require two queries.

Handle common events like calling function (for example, click (), submit () or mouseover ()) and its as simple as passing the event handler. You can also 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 of the events. To use these functions complete list, see Resources for a jQuery application programming interface (Application Program Interface, API) documentation.
The release of strong energy jQuery selector

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

jQuery selector syntax is based mainly on CSS3 and XPath in. On CSS3 and XPath know more when using jQuery will become even more handy. For a complete list of jQuery selectors, including CSS and XPath, see Resources for a link.

CSS3 contains some not all browsers support the syntax, so we rarely use it. However, we can still use the CSS3 in jQuery to select 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 identify all the elements of a particular class without it? CSS3 also provides a syntax to accomplish this purpose, using the: not pseudo-selector: The following code shows how to hide all non-required classes of input:

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

And just as in CSS, you can use a comma to connect multiple selectors 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 check box to add a border to the parent element, you can use XPath's / .. syntax:

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

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

$ ('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 element, whether this element is specific or vague, are likely to find a way to use a jQuery selector to define them.
Extend jQuery with plug-ins

Unlike most 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 may even want to write some plug-ins to make the code more simple. Here you can write the most basic jQuery plug-ins:

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

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

In this example, can be easily built on. 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 () return value, as 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-ins. For example, if you need to use each () function performs the same operation repeatedly, you can use a plug to complete.

Because jQuery plug-in very easy to write, so there are hundreds of options available for your use. jQuery plug-ins available for tabulation, rounded corners, slide show tool tips, date selectors, and all the effects we can think of. For a complete list of plug-ins, see the reference information.

The most complex, the most widely used plug-in to an interface (Interface), it is an animation 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 Scriptaculous is as same as for the Prototype.

Form plug-in is also popular and very useful, which allows you to easily use Ajax in the background 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 an Ajax call.
Conclusion

I'm just a brief introduction to the use of jQuery could accomplish. jQuery is fun to use, so we always look very simple to learn new skills and new features. From the beginning of the moment using jQuery, jQuery will be able to completely simplify your JavaScript and Ajax programming; each learn a little new knowledge, your code will be even easier.

Learn jQuery, I use the JavaScript programming language at the same time also received a lot of fun. Do not worry about all the boring contents, I can concentrate to write interesting content. Use of jQuery, I almost bid farewell to the era of writing code for loop. Even thought of using other JavaScript library, can not help but have balked. jQuery indeed changed my view of the JavaScript programming.
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Simplify Ajax development with jQuery

  • hibernate call stored procedure

    hibernate call stored procedure

  • hibernate using c3p0 connection pooling

    Private http://www.lifevv.com/tenyo/doc/20070605102040991.html 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.hbm2ddl.auto

    Hibernate in the configuration file: <properties> <property name="hibernate.hbm2ddl.auto" 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: @ 10.203.14.132:15

  • 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 java.io.Serializable; 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
Recent Entries
Tag Cloud
Random Entries