Using jquery to simplify Ajax development implementation method 1th/2 page _jquery

Source: Internet
Author: User
Some simple code simplification

The following is a simple example that illustrates the impact of JQuery on your code. To perform some really simple and common tasks, such as attaching a click event to each link in one area of a page, you can use pure JavaScript code and a DOM script, as shown in Listing 1.

Listing 1: A DOM script that does not use JQuery
Copy Code code 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 (' Your are going to visit: ' + this.href ');
};
}

Listing 2 shows the same functionality that was implemented using JQuery.
Listing 2. DOM script with JQuery
Copy Code code as follows:

$ (' #external_links a '). Click (function () {
return confirm (' Your are going to visit: ' + this.href ');
});

Isn't it amazing? With JQuery, you can grasp the main points of the problem and just let the code implement the functionality you want, eliminating some tedious process. You do not have to loop the elements, and the Click () function completes these operations. There is also no need for multiple DOM script calls. You only need to use a short string to define the elements that you want.
Understanding how this code works can be a bit tricky. First, we used the $ () function, the most powerful function in--jquery. Typically, we use this function to select elements from a document. In this case, a string containing some cascading style sheets (cascading style sheet,css) syntax is passed to the function, and jQuery can find the elements as efficiently as possible.
If you have a basic knowledge of CSS selectors, you should be familiar with these syntaxes. In Listing 2, #external_links is used to retrieve an element with an ID of external_links. A space after a indicates that JQuery needs to retrieve all the <a> elements in the external_links element. Speaking in English is very round the mouth, even in the DOM script, but in the CSS this is simple
The $ () function returns a JQuery object that contains all the elements that match the CSS selector. The jquery object is similar to an array, but it comes with a large number of special jquery functions. For example, you can assign the click handler to all the elements in the JQuery object by calling the Click function.
You can also pass an element or an array of elements to the $ () function that encapsulates the elements in a JQuery object. You might want to use the JQuery function for some objects, such as window objects, using this feature. For example, we typically assign functions to load events as follows:
Copy Code code as follows:

Window.onload = function () {
Do this stuff the page was done loading
};

Code with the same functionality written in JQuery:
Copy Code code as follows:

$ (window). Load (function () {
Run this when the whole page has been downloaded
});

As you may realize, waiting for the window to load is very slow and painful, because you have to wait for the entire page to load all the content, including all the pictures on the page. Sometimes, you want to finish loading the picture first, but in most cases you just load the Hypertext Markup Language (hypertext Markup language,html). JQuery solves this problem by creating special ready events in the document, as follows:
Copy Code code as follows:

$ (document). Ready (function () {
Do this stuff the HTML was all ready
});

This code creates a JQuery object around the document element and then builds a function to invoke the instance when the HTML DOM document is ready. You can call this function arbitrarily, as needed. And be able to call this function using shortcuts in real jQuery format. This is simple, just passing a function to the $ () function is OK:
Copy Code code as follows:

$ (function () {
Run this when the HTML was done downloading
});

So far, I've introduced three uses of the $ () function. The fourth method can use strings to create elements. The result produces a JQuery object that contains the element. The example shown in Listing 3 adds a paragraph to the page.
Listing 3. Create and attach a simple paragraph
Copy Code code as follows:

$ (' <p></p> ')
. html (' Hey world! ')
. css (' background ', ' yellow ')
. Appendto ("body");

As you may have noticed in the previous example, another powerful feature in JQuery is the method link (methods chaining). Each time a method is invoked on a jquery object, the method returns the same jquery object. This means that if you need to call multiple methods on a JQuery object, you do this without having to retype the selector: making Ajax simple
Copy Code code as follows:

$ (' #message '). CSS (' background ', ' yellow '). html (' hello! '). Show ();

Using JQuery will make Ajax as simple as it gets. JQuery provides a number of functions that make simple work easier, and complex work becomes less complex.
The most common use of Ajax is to load a piece of HTML code into an area of the page. To do this, simply select the element you want, and then use the load () function. The following is an example for updating statistics:
Copy Code code as follows:

$ (' #stats '). Load (' stats.html ');

Typically, we simply pass some parameters to a page in the server. As you would expect, using JQuery to do this is a very simple operation. You can use $.post () or $.get (), which is determined by the method you want. You can also pass an optional data object and callback function, if needed. Listing 4 shows a simple example of sending data and using callbacks.
Listing 4. Using Ajax to send data to a page
Copy Code code as follows:

$.post (' save.cgi ', {
Text: ' My string ',
Number:23
}, function () {
Alert (' Your data has been saved. ');
});

If you do need to write some complex Ajax scripts, you need to use the $.ajax () function. You can specify that XML, script, HTML, or json,jquery will automatically prepare the appropriate results for the callback function so that you can use the result immediately. You can also specify Beforesend, error, success, or complete callback functions to provide users with more feedback about the Ajax experience. In addition, there are other parameters available that you can use to set the timeout for the Ajax request, or to set the status of the page "last modified." Listing 5 shows an example of retrieving an XML document using some of the parameters I mentioned.
Listing 5 $.ajax () makes Ajax simpler by complexity
Copy Code code 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
}
});

When the success callback function returns an XML document, you can use JQuery to retrieve the XML document in the same way that it retrieves an HTML document. This makes processing XML documents quite easy, and integrates content and data into your Web site. Listing 6 shows an extension of the success function, which adds a list item to a Web page for each <item> element in the XML.
listing 6. Using JQuery to process XML documents
Copy Code code as follows:

Success:function (XML) {
$ (XML). Find (' item '). each (function () {
var Item_text = $ (this). text ();
$ (' <li></li> ')
. HTML (Item_text)
. Appendto (' ol ');
});
}

Current 1/2 page 12 Next read the full text

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.