Simplify Ajax development with jQuery

来源:百度文库 编辑:神马文学网 时间:2024/04/28 05:35:19
Created by John Resig in early 2006, jQuery is a great library foranyone who works with JavaScript code. Whether you‘re new to theJavaScript language and want a library to address some of thecomplexities of Document Object Model (DOM) scripting and Ajax oryou‘re an advanced JavaScript guru and tired of the boring repetitioninvolved with DOM scripting and Ajax, jQuery will suit you well.
jQuery helps you keep your code simple and succinct. You no longer have to write abunch of repetitious loops and DOM scripting library calls. With jQuery, you canget right to the point and express yourself in the fewest possible characters.
The jQuery philosophy is certainly unique: It‘s designed to keep things simple andreusable. When you understand and feel comfortable with the philosophy, you‘ll startto see just how much jQuery can improve the way you program.


Back to top
Here‘s a simple example of the impact jQuery can have on your code. To do somethingreally simple and common, such as attach a click event to every link in an area ofa page, you‘d use plain JavaScript code and DOM scripting, as shown inListing 1.
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 functionality achieved using jQuery.
$(‘#external_links a‘).click(function() {
return confirm(‘You are going to visit: ‘ + this.href);
});
Amazing, isn‘t it? With jQuery, you get right to the point, and express only what youwant the code to do without all the hassle. No need to loop over theelements; the click() function takes care of that. Also no need to make multiple DOM scripting calls: All that you need is ashort string to define the elements to work on.
It can be a bit tricky to understand how this code even gets the job done. First,you have the $() function -- the most powerful function injQuery. Mostly, you use this function to select elements from the document. In thisexample, the function is passed a string containing some Cascading Style Sheets(CSS) syntax, and jQuery finds the elements as efficiently as possible.
If you know the basics of CSS selectors, this syntax should look familiar. InListing 2, #external_links looks for the element with anid of external_links. A spacefollowed by a tells jQuery to look for all the elements inside the external_linkselement. That‘s a mouthful to say in English -- and even in DOM scripting -- but inCSS, it couldn‘t be simpler.
The $() function returns a jQuery object containing allthe elements that match the CSS selector. A jQuery object is something likean array but comes with a ton of special jQuery functions. For example, you canassign a click handler function to each element in the jQuery object by calling theclick function.
You can also pass an element or an array of elements to the $() function, and it will wrap a jQuery object around the elements. You might want touse this functionality to employ jQuery functions on things like thewindow object. For example, you typically assignthe function to the load event like this:
window.onload = function() {
// do this stuff when the page is done loading
};
Using jQuery, you write the same code like this:
$(window).load(function() {
// run this when the whole page has been downloaded
});
As you probably already know, waiting for the window to load is painfully slow,because the whole page must finish loading, including all the images on the page.Sometimes, you want the images to finish loading first, but most of the time, youjust need the Hypertext Markup Language (HTML) to be there. jQuery solves thisproblem by creating a special ready event on thedocument, used like this:
$(document).ready(function() {
// do this stuff when the HTML is all ready
});
This code creates a jQuery object around the documentelement, then sets up a function to call the instance when the HTML DOM documentis ready. You can call this function as many times as necessary. And, in truejQuery style, a shortcut calls this function. Simply pass afunction to the $() function:
$(function() {
// run this when the HTML is done downloading
});
So far, I‘ve shown you three different ways to use the $()function. With a fourth way, you can create an element using a string. Theresult is a jQuery object containing that element.Listing 3shows an example that adds a paragraph to the page.
$(‘

‘)
.html(‘Hey World!‘)
.css(‘background‘, ‘yellow‘)
.appendTo("body");
$(‘#message‘).css(‘background‘, ‘yellow‘).html(‘Hello!‘).show();


Back to top
Ajax couldn‘t be any easier than it is with jQuery. jQuery has a handful offunctions that make the easy stuff really easy and the complex stuff as simpleas possible.
A common use of Ajax is to load a chunk of HTML into an area of the page. To dothat, simply select the element you need and use the load()function. Here‘s an example that updates some statistics:
$(‘#stats‘).load(‘stats.html‘);
Often, you simply need to pass some parameters to a page on the server. As you‘dexpect, this is incredibly simple in jQuery, too. You can use choose between$.post() and $.get(),depending on which method you need. You can pass an optional data object andcallback function if you need them.Listing 4 shows a simpleexample that sends data and uses a callback.
$.post(‘save.cgi‘, {
text: ‘my string‘,
number: 23
}, function() {
alert(‘Your data has been saved.‘);
});
If you really want to do some complex Ajax scripting, you need the$.ajax() function. You can specifyxml, html,script, or json, and jQueryautomatically prepares the result for your callback function so that you can use itright away. You can also specify beforeSend,error, success, orcomplete callbacks to give the user more feedback aboutthe Ajax experience. In addition, other parameters are available with which you canset the timeout of an Ajax request or the "Last Modified" state of a page.Listing 5 shows an example that retrieves an XML documentusing some of the parameters that I mentioned.
$.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 you get the XML back in the success callback, you can use jQuery to lookthrough the XML the same way you do with HTML. This makes it easy to work withan XML document and integrate the contents and data into your Web site.Listing 6 shows an expansion on the successfunction that adds a list item to the Web page for each element in the XML.
success: function(xml){
$(xml).find(‘item‘).each(function(){
var item_text = $(this).text();
$(‘
  • ‘)
    .html(item_text)
    .appendTo(‘ol‘);
    });
    }


    Back to top
    You can use jQuery to take care of basic animations and effects. At the heart of theanimation code is the animate() function, which changesany numeric CSS style value over time. For example, you can animate height, width,opacity, or position. You can also specify the speed of the animation, either inmilliseconds or in one of the predefined speeds: slow, normal, or fast.
    Here‘s an example that animates the height and width of an element at the same time.Notice that there is no start value -- only the end value. The start values aretaken from the current size of the element. I‘ve also attached a callback function.
    $(‘#grow‘).animate({ height: 500, width: 500 }, "slow", function(){
    alert(‘The element is done growing!‘);
    });
    jQuery makes the more common animations easier with built-in functions. You can useshow() and hide() elements,either instantly or at a specified speed. You can also make elements appear anddisappear by using fadeIn() and fadeOut()or slideDown() and slideUp(),depending on what kind of effect you‘re looking for. Here‘s a simple example thatslides down a navigation:
    $(‘#nav‘).slideDown(‘slow‘);


    Back to top
    jQuery is, perhaps, best at simplifying DOM scripting and event handling. Traversingand manipulating the DOM is easy, and attaching, removing, and calling events iscompletely natural and much less error prone than doing it by hand.
    In essence, jQuery makes it easier to do things that are common with DOM scripting.You can create elements and use the append() function tolink them to other elements, use clone() to duplicateelements, set the contents with html(),delete the contents with the empty() function,delete the elements altogether with the remove()function, and even use the wrap() function to wrap theelements with another element.
    Several functions are available for changing the contents of the jQuery objectitself by traversing the DOM. You can get all the siblings(),parents(), or children() of anelement. You can also select the next() orprev() sibling elements. Perhaps most powerful is thefind() function, which allows you to use a jQueryselector to search through the descendants of elements in your jQuery object.
    These functions become more powerful when used with the end()function. This function is like an undo function, going back to the jQuery objectyou had before you called find() or parents()or one of the other traversing functions.
    When used together with method chaining, these functions allow complex operationsto look simple.Listing 7 shows an example in which you find alogin form and manipulate several elements around it.
    $(‘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‘, ‘1px solid red‘).end()
    // add a submit handler to the form
    .submit(function(){
    return confirm(‘Are you sure you want to submit?‘);
    });
    Believe it or not, this example is just a single, chained, line of code spread outwith whitespace. First, I selected the login form. Then, I found the optionallabels inside it, hid them, and called end() to go backto the form. I found the password field, made the border red, and again calledend() to go back to the form. Finally, I added a submitevent handler to the form. What‘s especially interesting about this (besides itsobvious brevity) is that jQuery completely optimizes all the query operations,making sure that you don‘t have to find an element twice when everything is nicelychained together.
    Handling common events is as simple as calling a function like click(),submit(), or mouseover() andpassing it an event handler function. Additionally, you have the option of assigninga custom event handler using bind(‘eventname‘, function(){}).You can remove certain events using unbind(‘eventname‘) orall events with unbind(). For a complete list of ways to usethese and other functions, check out the jQuery application program interface (API)documentation in theResources.


    Back to top
    Often, you select elements by ID, such as #myid, or byclass name, such as div.myclass. However, jQuery has arather complex and complete selector syntax that allows you to select nearly anycombination of elements in a single selector.
    jQuery‘s selector syntax is based heavily on CSS3 and XPath. The more you know aboutCSS3 and XPath syntax, the better you‘ll be at using jQuery. For a complete list ofjQuery selectors, including CSS and XPath, check out the links inResources.
    CSS3 contains some syntax that not every browser supports, so you don‘t see itoften. However, you can still use CSS3 in jQuery to select elements, because jQuery hasits own, custom selector engine. For example, to add a dash inside every emptycolumn of a table, use the :empty pseudo-selector:
    $(‘td:empty‘).html(‘-‘);
    What about finding every element that doesn‘t have a certain class? CSS3 hasa syntax for that, too, using the :not pseudo-selector.Here‘s how you can hide every input that doesn‘t have a class ofrequired:
    $(‘input:not(.required)‘).hide();
    You can also join multiple selectors into one using commas, just as in CSS. Here‘s asimple example that hides every type of list on the page at the same time:
    $(‘ul, ol, dl‘).hide();
    XPath is a powerful syntax for finding elements in a document. It‘s a bit differentthan CSS and lets you do a few things you can‘t do with CSS. To add a border to theparent element of every check box, you can use XPath‘s /..syntax:
    $("input:checkbox/..").css(‘border‘, ‘1px solid #777‘);
    jQuery adds extra selectors that aren‘t available in CSS or XPath, as well. Forexample, to make a table more readable, you would typically attach a differentclass name to every odd or even row of the table -- otherwise known as stripingthe table. Doing this with jQuery is a cinch, thanks to the:odd pseudo-selector. This example changes thebackground of every odd row in tables with a stripedclass:
    $(‘table.striped > tr:odd‘).css(‘background‘, ‘#999999‘);
    You can see how the powerof jQuery selectors can simplify your code. Whatever selection ofelements you want to affect, no matter how specific or obscure, you canprobably find a way to define them using a single jQuery selector.


    Back to top
    Unlike with most software, writing plug-ins for jQuery isn‘t a huge ordeal with acomplex API. In fact, jQuery plug-ins are so easy to write that you might want towrite a few to make your code even simpler. Here‘s the most basic jQueryplug-in you can write:
    $.fn.donothing = function(){
    return this;
    };
    Although simple, this plug-in does require a bit of explanation. First, to add afunction to every jQuery object, you must assign it to $.fn.Next, this function must return this (the jQuery object)so that it doesn‘t breakmethod chaining.
    You can easily build on top of this simple example. To write a plug-in to change thebackground instead of using css(‘background‘), you use this:
    $.fn.background = function(bg){
    return this.css(‘background‘, bg);
    };
    Notice that I could just return the value from css(),because it already returns the jQuery object. So, method chaining will still workfine.
    I recommend that you use jQuery plug-ins anytime you find that you repeatyourself. For example, you might use a plug-in if you‘re using theeach() function to do the same thing over and over.
    Because jQuery plug-ins are so easy to write, hundreds of them are available for youto use. jQuery has plug-ins for tabs, rounded corners, slide shows, tool tips, dateselectors, and probably anything else you can imagine. For a complete list ofplug-ins, check out theResources.
    The most complex and most widely used plug-in is Interface, an animation plug-inthat handles sorting, drag-and-drop functionality, complex effects, and otherinteresting and complex user interfaces (UIs). Interface is to jQuery whatScriptaculous is to Prototype.
    Also popular and useful is the Form plug-in, which allows you to easily submit aform in the background using Ajax. This plug-in takes care of the common situationin which you need to hijack the submit event of a form, then find all the differentinput fields and use them to construct an Ajax call.


    Back to top


    Digg this story

    Post to del.icio.us

    Slashdot it!

    I‘veonly scratched the surface of what is possible with jQuery. jQuery isfun to use, because you always learn new tricks and features that seemso natural. jQuery simplifies your JavaScript and Ajax programmingcompletely from the first moment you use it; every time you learnsomething new, your code gets a bit simpler.
    After learning jQuery, I‘ve had a lot more fun programming in the JavaScriptlanguage. All the boring stuff is taken care of, so I can focus on coding the juicystuff. With jQuery, I can barely remember the last time I wrote afor loop. I even cringe at the thought of working withother JavaScript libraries. jQuery has honestly and truly changed the way I look atJavaScript programing forever.
    Learn
    developerWorks XML zone: Learn all about XML at the developerWorks XML zone.
    jQuery API documentation: Explore the complete documentation of jQuery with links to tutorials as well as the API reference.
    jQuery tutorials: Check out a great collection of multilingual jQuery tutorials, including 40 in English.
    Visual jQuery: Read an interactive and easy-to-navigate jQuery API reference.
    IBM XML certification:Find out how you can become an IBM-Certified Developer in XML and related technologies.
    XML technical library: See the developerWorks XML Zone for a wide range of technical articles and tips, tutorials, standards, and IBM Redbooks.
    Get products and technologies
    jQuery: Visit the main jQuery site and download the source code.
    Selectors: Get a complete list of all the selectors you can use with jQuery, including CSS3 and XPath selectors.
    jQuery plug-ins: Find a nearly complete list of available jQuery plug-ins.
    Interface: Try the ultimate jQuery plug-in for animation, effects, drag-and-drop functionality, and UIs.
    Form plug-in: Get a jQuery plug-in that lets you submit a form using Ajax.
    Discuss
    jQuery blog: Frequent the official jQuery blog for regular news and updates.
    XML zone discussion forums: Participate in any of several XML-centered forums.