Use jquery to simplify Ajax development [posting]

Source: Internet
Author: User

Jesse Skinner, Web Developer, freelance

May 16, 2007

Jquery is a javascript library that helps simplify JavaScript and Asynchronous JavaScript + XML (Ajax) programming. Unlike similar JavaScript libraries, jquery has unique basic principles that can easily represent common and complexCode. Learn the basic principles of jquery, explore its features and functions, execute some common Ajax tasks, and learn how to use plug-ins to expand jquery.

What is jquery?

Jquery was created by John resig in early 2006.ProgramIt is a very useful JavaScript library. Whether you are new to the Javascript language and want to obtain a library that can solve some complex problems in Document Object Model (DOM) scripts and Ajax development, jquery is your first choice as a senior JavaScript expert tired of Dom scripts and boring repetitive work in Ajax development.

Jquery helps you ensure that the Code is concise and easy to read. You no longer have to write a bunch of repeated loop code and Dom script library calls. With jquery, You can grasp the key points of the problem and use as few code as possible to implement the functions you want.

There is no doubt that jquery's principle is unique: its purpose is to ensure that the Code is concise and reusable. After understanding and understanding this principle, you can start to learn this tutorial and see how many improvements jquery has made to our programming methods.



Back to Top

Simplified code

The following is a simple example to illustrate the impact of jquery on code. To execute some really simple and common tasks, for example, attaching a click event to each link in a certain area of the page, you can use pure JavaScript code and Dom scripts, as shown in Listing 1.

Listing 1. The jquery Dom script is not used

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 same functions implemented using jquery.

Listing 2. Using the jquery Dom script

$ ('# External_links A'). Click (function () {return confirm ('you are going to visit: '+ this. href );});

Is it amazing? With jquery, You can grasp the key points of the problem and only let the code implement the functions you want, saving some tedious processes. Element loops are not required,Click ()The function completes these operations. You do not need to call multiple Dom scripts. You only need to use a short string to define the required elements.

Understanding how this code works may be a little complicated. First, we use$ ()Function-the most powerful function in jquery. We usually use this function to select elements from the document. In this example, a string containing some Cascading Style Sheet (CSS) syntax is passed to the function, and jquery finds these elements as efficiently as possible.

If you have basic knowledge about CSS selectors, you should be familiar with these syntaxes. In Listing 2,# External_linksUsed for retrievalIDIsExternal_links.AThe following space indicates that jquery needs to searchExternal_linksAll<A>Element. It is very difficult to say in English, even in Dom scripts, but in CSS, this is no more simple.

$ ()The function returns a jquery object containing all elements that match the CSS selector.Jquery objectIt is similar to an array, but it comes with a large number of special jquery functions. For example, you can callClickThe function specifies the click handler to all elements in the jquery object.

You can also$ ()The function passes an element or an element array, which encapsulates these elements in a jquery object. You may want to use this function to use jquery functions for some objects, for exampleWindowObject. For example, we usually allocate a function to a loading event as follows:

Window. onload = function () {// do this stuff when the page is done loading };

Code with the same functions written using jquery:

$ (Window). Load (function () {// run this when the whole page has been downloaded });

You may be aware that the process of waiting for window loading is very slow and painful, because it is necessary to wait until the entire page loads all the content, including all the images on the page. Sometimes you want to load images first, but in most cases, you only need to load Hypertext Markup Language (HTML. Create a specialReadyEvent, jquery solves this problem:

$ (Document). Ready (function () {// do this stuff when the HTML is all ready });

This code is centered aroundDocumentElement creates a jquery object and creates a function to call the instance when the HTML Dom document is ready. You can call this function as needed. In addition, you can use shortcuts to call this function in the real jquery format. This is simple.$ ()You can pass a function through the function:

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

So far, I have already introduced$ ()Function usage. The fourth method can use strings to create elements. A jquery object containing the element is generated. The example shown in listing 3 adds a section to the page.

Listing 3. Creating and attaching a simple Section

$ ('<P> </P>'). html ('Hey world! '). CSS ('background', 'yellow'). appendto ("body ");

In the previous example, you may have noticed that another powerful feature of jquery isMethod chaining). Each time you call a method on a jquery object, the same jquery object is returned for the method. This means that if you need to call multiple methods for the jquery object, you do not have to re-type the selector to achieve this purpose:

Certificate ('your message'0000.css ('background ', 'yellow'0000.html ('Hello! '). Show ();


Back to Top

Making Ajax simple

Using jquery makes Ajax easier. Jquery provides some functions to make simple work easier and complex work no longer complicated.

The most common use of AJAX is to load an HTML code to a certain area of the page. To do this, simply select the required elements and then useLoad ()Function. The following is an example of updating statistics:

('{Stats'{.load('stats.html ');

Generally, we only need to pass some parameters to a page on the server. As you expected, using jquery is very simple. You can use$. Post ()Or$. Get (), Which is determined by the required method. If necessary, you can also pass an optional data object and callback function. Listing 4 shows a simple example of sending data and using callback.

Listing 4. 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 scripts, you need to use$. Ajax ()Function. You can specifyXML,Script,HtmlOrJSON, Jquery will automatically prepare appropriate results for the callback function, so that you can use the results immediately. You can also specifyBeforesend,Error,SuccessOrCompleteCallback function to provide users with more feedback on the Ajax experience. In addition, some other parameters are available. You can use them to set the Ajax request timeout, or set the "last modification" status on the page. Listing 5 shows an example of retrieving an XML document using some of the parameters I mentioned.

Listing 5. $. Ajax () makes Ajax complex and simple

$. Ajax ({URL: 'document. xml', type: 'get', ype: 'xml', timeout: 1000, error: function () {alert ('error loading XML document');}, success: function (XML) {// do something with XML }});

After the success callback function returns an XML document, you can use jquery to retrieve this XML document in the same way as retrieving HTML documents. This makes it quite easy to process XML documents and integrates content and data into your web site. Listing 6 showsSuccessAn extension of a function.<Item>Add a list item to the web page.

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 ');});}


Back to Top

Add an animation to HTML

You can use jquery to process basic animations and display effects.Animate ()A function is the core of the animation Code. It is used to change any numeric CSS style values that change over time. For example, you can change the height, width, opacity, and position. You can also specify the animation speed as millisecond or predefined speed: slow, medium or fast.

The following is an example of changing the height and width of an element at the same time. Note that these parameters have no starting values, but only the final values. The start value is taken from the current size of the element. 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 make it easier to complete more common animations. AvailableShow ()AndHide ()To display immediately or at a specific speed. You can also useFadein ()AndFadeout (), OrSlidedown ()AndSlideup ()Show and hide elements, depending on the display effect you need. The following example defines a sliding navigation menu.

$ ('# Nav'). slidedown ('low ');


Back to Top

Dom script and Event Processing

Perhaps jquery is best at simplifying Dom scripts and event processing. It is very simple to traverse and process the Dom, and it is also very easy to append, remove and call events, and it is not as error-prone as manual operations.

In essence, jquery makes common operations in Dom scripts easier. You can create elements and useAppend ()Function links them with other elements and usesClone ()Copy element, useHTML ()Set content, useEmpty ()Function to delete content, useRemove ()Function deletes all elements, even if you useWrap ()Function to wrap these elements with other elements.

By traversing the Dom, some functions can be used to change the content of the jquery object itself. You can obtain allSiblings (),Parents ()AndChildren (). You can also selectNext ()AndPrev ()Sibling element.Find ()A function is perhaps the most powerful function. It allows you to use the jquery selector to search for descendant elements of elements in a jquery object.

If you useEnd ()Then these functions become more powerful. This function is similar to the Undo function and is used to return to the call.Find ()OrParents ()Jquery objects before functions (or other traversal functions.

If you use the method chaining together, these functions can make complex operations very simple. Listing 7 shows an example with a logon form and related elements.

Listing 7. Easily traverse and process the 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'0000.css ('border', '1px solid red '). end () // Add a submit handler to the form. submit (function () {return confirm ('Are you sure you want to submit? ');});

Whether you believe it or not, this example is just a line of code with blank links. First, select the logon form. Then, it is found that there are optional tags, hide them, and callEnd ()Return form. Then, I created a password field, changed its border to red, and called againEnd ()Return form. Finally, I added a submit event handler in the form. Among them, it is particularly interesting (except for its simplicity) That jquery completely optimizes all query operations and ensures that all content is properly linked together, you do not need to perform two queries on an element.

Processing common events is like calling a function (for exampleClick (),Submit ()OrMouseover ()Is as simple as passing event processing functions. You can also useBIND ('eventname', function (){})Specifies a Custom Event Handler. AvailableUnbind ('eventname ')Delete some events or useUnbind ()Delete all events. For a complete list of how to use these functions, see the jquery application programming interface (API) Documentation in reference.

Releases the powerful energy of the jquery selector.

We often use ID to select elements, such# MyidOr use the class name, suchDiv. myclassTo select elements. However, jquery provides a more complex and complete selector syntax that allows us to select almost all combinations of elements in a single selector.

Jquery's selector syntax is mainly based on css3 and XPath. The more you know about css3 and XPath, the more convenient it is to use jquery. For a complete list of jquery selectors, including CSS and XPath, see references.

Css3 contains some syntaxes not supported by all browsers, So we seldom use them. However, we can still use css3 Selection Elements in jquery, because jquery has its own custom selector engine. For example, to add a horizontal bar to each empty column in the table, you can use:: EmptyPseudo selector ):

$ ('Td: empty'hangzhou.html ('-');

If you need to find allNoWhat about the elements of a specific class? Css3 also provides a syntax for this purpose.: NotPseudo selector: the following code shows how to hide allRequiredClass input content:

$ ('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 the page at the same time:

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

XPath is a powerful syntax used to search for elements in a document. It is slightly different from CSS, but it can implement more functions than CSS. To add a border to the parent element of all check boxes, you can use/..Syntax:

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

Some selectors that are not included in CSS and XPath are also added to jquery. For example, to make a table more readable, you can usually append a different class name to an odd or even row of the table.Segment (striping). This can be done with jquery without any effort, thanksOddPseudo selector. The following example usesStripedClass changes the background color of all odd rows in the table:

$ ('Table. Striped> TR: odd'hangzhou.css ('background', '#999999 ');

We can see how the powerful jquery selector simplifies the code. No matter what elements you want to deal with, whether specific or fuzzy, you may find a way to define them using a jquery selector.

Extension of jquery using plug-ins

Unlike most software, using a complex API to compile plug-ins for jquery is not very difficult. In fact, jquery plug-ins are very easy to write, and you even want to write some plug-ins to make the code simpler. Below are the most basic jquery plug-ins that can be written:

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

Although very simple, you still need to explain this plug-in. First, if you want to add a function for each jquery object, you must assign this function$. FN. Second, this function must returnThis(Jquery object), so as not to interrupt the method chaining ).

You can easily build on this example. You need to write a plug-in to replace the background color.CSS ('background '), You can use the following code:

$. FN. Background = function (BG) {return this.css ('background', BG );};

Note that onlyCSS ()Returned value because the jquery object has been returned. Therefore, method chaining still works well.

I recommend that you use the jquery plug-in when you need to repeat the work. For exampleEach ()If the function executes the same operation repeatedly, you can use a plug-in.

Because jquery plug-ins are quite easy to write, there are hundreds of plug-ins available for you to choose from. The plug-in provided by jquery can be used for tabulation, rounded corners, slide display, tooltip, date selector, and everything we can think. For a complete list of plug-ins, see references.

Interfaces are the most complex and widely used plug-ins. They are an animation plug-in, it is used to process sorting, drag-and-drop functions, complex effects, and other interesting and complex user interfaces (UIS ). The interface is the same for jquery as scriptaculous for prototype.

Form plug-ins are also popular and useful. You can use ajax to easily submit forms in the background. This plug-in is used to handle some common situations: You need to intercept the submission events of a form, find all different input fields, and construct an Ajax call using these fields.

Conclusion

I just briefly introduced the tasks that may be completed using jquery. Jquery is very interesting to use, so we can always learn new techniques and features that seem simple. From the moment you start using jquery, jquery can completely simplify your JavaScript and Ajax programming. Every time you learn a little new knowledge, your code will be simpler.

After learning jquery, I had a lot of fun programming in JavaScript. I don't have to worry about all the boring content. I can focus on writing interesting content. After using jquery, I almost said goodbye to writingForThe era of circular code. Even when you want to use other JavaScript libraries, you can't help but get stuck. Jquery has indeed changed my views on JavaScript programming.

References

Learning

    • For more information, see the original article on the developerworks global website.

    • Ajax technical resource center: All Ajax-related questions can be found here on developerworks.
    • Developerwork China website XML area: learn about all aspects of XML.
    • Jquery API documentation: describes the complete jquery documentation through links to some tutorials and API references.
    • Jquery Tutorial: Refer to jquery tutorials in different languages, including 40 English articlesArticle.
    • Visualized jquery: Read this interactive and easy-to-navigate jquery api reference.
    • Ibm xml Certification: see how to become an IBM-certified XML and related technology developer.
    • XML technical documentation Library: The developerworks XML area provides a large number of technical articles, tips, tutorials, standards, and IBM redbooks.

Obtain products and technologies

    • Jquery: visit and download the jquery homepage.Source code.

    • Selector: obtains the complete list of selector that can be used in jquery, including css3 and XPath selector.
    • Jquery Plugin: Get a complete list of available jquery plug-ins.
    • Interface: Try jquery's most basic plug-in for animation, display effect, drag-and-drop, and user interface (UI ).
    • Form Plugin: gets the jquery plugin, which can be used to submit forms using Ajax.

Discussion

    • Jquery blog: for daily news and updates about jquery, visit the official jquery blog frequently.

    • XML Forum: participate in any XML-centered forum.

      ----------------
      Pig blog (pig nest) http://www.zhublog.com/
      Cool Network http://www.kuiu.cn/

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.