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.

分类:Web 时间:2010-05-05 人气:305
blog comments powered by Disqus


  • 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

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

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

  • 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,

  • JS.DOM和JQuery之间的关系示例分析 2014-07-16

    这篇文章主要介绍了JS.DOM和JQuery之间的关系,对此概念不是特别清楚的朋友可以参考下 DOM(document object model) 其实是浏览器内元素对象的一个总称 我们用JavaScript对网页进行的所有操作都是通过DOM进行的.DOM属于浏览器,而不是JavaScript语言规范里的规定的核心内容,所以如果你下载一个JavaScript语言的参考帮助文档来查的话,就连妇孺皆知的document.write方法也找不到. 文档对象模型(Document Object Mode

  • selenium1.X web Test experience 2011-06-29

    简介 Selenium 是一个健壮的工具集合,跨很多平台支持针对基于 web 的应用程序的测试自动化的敏捷开发.它是一个开源的.轻量级的自动化工具,很容易集成到各种项目中,支持多种编程语言,比如 .NET.Perl.Python.Ruby 和 Java™ 编程语言. 利用 Selenium 测试 Ajax 应用程序 Asynchronous JavaScript and XML (Ajax) 是一种用于创建交互式 web 应用程序的 web 开发技术.Ajax 应用程序的一个特征是,不会导致一次

  • Principle of detailed description of Ajax 2009-07-10

    Ajax from the HTML, JavaScript? Technology, DHTML, and DOM composition, this method can be distinguished clumsy Web interface, into interactive Ajax applications. This series was written by an Ajax expert, demonstrates how these technologies work tog

  • Simplify Ajax development with jQuery 2010-10-20

    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.

  • Ajax detailed description of the principle 2009-04-17

    Ajax by the HTML, JavaScript ™ technology, DHTML and DOM composition, this method can be distinguished clumsy Web interface will be transformed into interactive Ajax applications. The author of this article is a Ajax experts, he demonstrated how thes

  • 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 0.035 (s). 13 q(s)