Simplify Ajax development with 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 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.

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.

分类:Web 时间:2010-10-20 人气:306
blog comments powered by Disqus


  • js/ajax跨越访问-jsonp的原理和实例(javascript和jquery实现代码) 2014-05-18

    最近做了一个项目,需要用子域名调用主域名下的一个现有的功能,于是想到了用jsonp来解决,在我们平常的项目中不乏有这种需求的朋友,于是记录下来以便以后查阅同时也希望能帮到大家,需要了解的朋友可以参考下 很庆幸,我又见到了末日后新升的太阳,所以我还能在这里写文章,言归正传哈,最近做了一个项目,需要用子域名调用主域名下的一个现有的功能,于是想到了用jsonp来解决,在我们平常的项目中不乏有这种需求的朋友,于是记录下来以便以后查阅同时也希望能帮到大家. 什么是JSONP协议? JSONP即JSON w

  • Simple description of the principle ------ ajax 2011-04-27

    AJAX = Asynchronous (induction) JavaScript and XML Word principle: XmlHttpRequest object through the asynchronous request sent to the server, access to data from the server, and then use javascript to manipulate the DOM and update the page. Keywords:

  • AJAX + XML-based XLoadTree dynamic loading of components of the document tree JS 2009-06-26

    Tree node has recently started to load and read a good article, look around them to share BeanSoft evaluation: This component tree is not perfect, but it is based on self-object-oriented, based on the AJAX + XML + DOM, the head is also relatively sma

  • jquery的ajax全局事件详解-明河谈jquery 2013-02-04

    jquery在ajax方面是非常强大和方便的,以下是jquery进行ajax请求时方法模板: $.ajax({ type: "get", url: "", data : {}, beforeSend : function(){ }, success : function(data){ }, complete : function(){ } }); 关于$.ajax()方法的使用,不是明河写这篇文章的目的,今天明河主要讲解当进行ajax请求时整个完整的事件流程. jq

  • jquery ajax后台向前台传list 前台用jquery $.each遍历list 2014-06-15

    下边是两种前台接收并遍历list Js代码 $.ajax({ type: 'post', url: xxx.action', dataType: 'text', success: function(data){ var dataObj=eval("("+data+")"); for(var i=0;i<dataObj.length;i++){ alert(dataObj[i].id+" "+dataObj[i].name); } var j

  • AJAX memory leak in the function under the JQUERY solution 2010-04-02

    First JQUERY objects into DOM DOM object to call the native function can be used JQUERY Object -> DOM Object $('')[ 0] html () $('')[ 0]. InnerHTML =''; Document Processing append () var child = document.createElement ("..."); $('')[ 0]. Appe

  • Memory leak patterns in JavaScript 2010-03-17

    From dW JavaScript is used to add dynamic content to the Web page is a powerful scripting language. In particular, it especially useful for routine tasks such as authentication password, and create a dynamic menu component. JavaScript easy to learn,

  • AJAX and the relationship between JS and XHR 2010-06-13

    Has been the relationship between these three is not very clear on this record these relationships: Explanation in Wikipedia: AJAX full name "Asynchronous JavaScript and XML" (Asynchronous JavaScript

  • <Head Rush Ajax> - Study Notes easy to understand Ajax 2010-06-05

    1, asynchronous applications is to use JavaScript objects to make a request, not submit the form. 2, the request and response processing by the Web browser, and not directly by the JavaScript code to handle. 3, once the web browser to get asynchronou

  • Ajax principle. Development. Merits. Problems 2009-04-18

    AJAX because of his relatively late, in the face of various ways to achieve AJAX I feel confusion, the tunnel will be their understanding of AJAX now you organize, but also facilitate future themselves be able to further a better understanding of AJA

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C), All Rights Reserved. 版权所有 闽ICP备15018612号

processed in 1.785 (s). 10 q(s)