Use jquery to simplify Ajax Development and Implementation page 1/2

Source: Internet
Author: User

Some simple Code Simplified

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: No Dom script using jquery
Copy codeThe Code is as follows: 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.
List 2. use the jquery Dom script
copy Code the code is as follows: $ ('# external_links '). 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. You do not need to cycle the elements. The click () 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 the $ () 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_links is used to retrieve the element whose ID is external_links. The space after a indicates that jquery needs to retrieve all elements in the external_links element. This is an easy way to speak in English, even in Dom scripts, but in CSS, it is no longer as simple as
$ () the function returns a jquery object containing all elements that match the CSS selector. Jquery objects are similar to arrays, but they come with a large number of special jquery functions. For example, you can call the click function to specify the click handler to all elements in the jquery object.
You can also pass an element or an element array to the $ () function, which encapsulates these elements in a jquery object. You may want to use this function to use jquery functions for some objects, such as window objects. For example, we usually assign a function to a loading event as follows: copy Code the code is as follows: window. onload = function () {
// do this stuff when the page is done loading
};

Code with the same functions written using jquery:Copy codeThe Code is as follows: $ (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. By creating a special ready event in the document, jquery solves this problem by using the following methods:Copy codeThe Code is as follows: $ (document). Ready (function (){
// Do this stuff when the HTML is all ready
});

This Code creates a jquery object around the document element 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 only need to pass a function to the $ () function:Copy codeThe Code is as follows: $ (function (){
// Run this when the HTML is done downloading
});

So far, I have introduced three usage methods of the $ () function. 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
Copy codeThe Code is as follows: $ ('<p> </P> ')
. Html ('Hey world! ')
. CSS ('background', 'yellow ')
. Appendto ("body ");

In the previous example, you may have noticed that another powerful feature of jquery is method 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 goal: to make Ajax simpleCopy codeThe Code is as follows: ('your message'}.css ('background ', 'yellow'}.html ('Hello! '). Show ();

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 use the load () function. The following is an example of updating statistics:Copy codeThe Code is as follows: ('{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.
list 4. use ajax to send data to the page copy Code the code is as follows: $. 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 the $. Ajax () function. You can specify XML, script, HTML, or JSON. jquery automatically prepares suitable results for the callback function, so that you can use the results immediately. You can also specify beforesend, error, success, or complete callback functions 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.
List 5. $. ajax () makes Ajax complex and simple copy Code the code is as follows: $. ajax ({
URL: 'document. xml',
type: 'get',
datatype: 'xml',
Timeout: 1000,
error: function () {
alert ('error loading XML document');
},
success: function (XML) {
// do something with XML
}< BR >});

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 shows an extension of the success function, which adds a list item to the web page for each <item> element in XML.
Listing 6. Using jquery to process XML documents
Copy codeThe Code is as follows: Success: function (XML ){
$ (XML). Find ('item'). Each (function (){
VaR item_text = $ (this). Text ();
$ ('<Li> </LI> ')
. Html (item_text)
. Appendto ('ol ');
});
}

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.