Ajax is changing web applications and bringing an unprecedented shock beyond desktop applications. However, behind these publicity efforts, we should realize that ajax is nothing new than -- (X) HTML, Javascript, and XML. in this tutorial, I will show you how to add ajax to your application and how to use a popular javascript library Jquey for ajax development.
1. What is ajax?
You may have heard of ajax before, or at least used ajax applications, such as Gmail. to put it simply, ajax uses javascript to process data asynchronously, instead of reloading the entire page at once. there is a tutorial on SitePoint a good introduction to Ajax. in addition, ajax is a famous article by Jesse James Garret.
Unfortunately, there are few practical tutorials on ajax, And the XMLHttpRequest class used in ajax is very difficult for beginners of web development. fortunately, a large number of javascript libraries have emerged one after another, providing a simple way to implement ajax. jquery, which we will use today, is one of them.
2. What is JQuery?
Jquery is a mature Javascript library that provides features not available in many other libraries. of course, you have to admit that it is 19 K big and doesn't want moo. fx is only 3KB light. you can see the performance of many javascript libraries and other comparative data here.
3. Prior Knowledge
To learn about this tutorial, you only need to have basic javascript. If you know the c-style language, you can quickly get started with javascript. it is actually a braces, a function declaration, and a semicolon (required for Jquery ). if you want to learn javascript, read this tutorial. in addition, since we are talking about web applications, basic html is naturally essential.
4. Jquery 101
Let's take a look at jQuery. to use jQuery, you must first download this library. here (current version 1.1.2 ). jQuery syntax is very simple: Find and then do. we select an element from the document and use $ (). this symbol is equivalent to document. getElementById (), but in addition to ID, it also supports css and some XPath. in addition, it can return an array of elements. okay. Maybe an example can better illustrate the $ () function.
We want to use the function to operate our selection operator. For example, we want to set "Hello World! "Add it to the div where every class is foo and set the color to Red. We can write the code like this:
$ ("Div. foo"). append ("Hello World! ").Css (" color "," red ");
Easy! In general, this requires two lines of code to complete:
Copy codeThe Code is as follows:
$ ("Div. foo"). append ("Hello World! ");
$ ("Div. foo" ).css ("color", "red ");
JQuery's link method can be to allow you to write your code. I'm afraid this is not the case for other libraries. many jQuery functions do not require objects, that is, they work independently. for example, we will use the post function. The call method is $. post (parameters ). for more information about jQuery functions, visit online documentation or visualjquery.com.
5. Example 1: our first ajax Program
As an example, we will build an interactive concept generator. simply put, let's randomly select two options from the list and combine them into a phrase. in this example, we will use words with web features (such as 'mashup', 'folksonmy', and 'Media '). These options are usually obtained from text files. to save time for users to download each combination (or at least each element) using javascript, we will quickly generate it on the server side and obtain it on the client side using jQuery. jQuery can be used in combination with javascript, so you will find that using it in code will make your work very easy.
Server code (php ):
For simplicity, we use the simplest code to create our concept generator. don't worry about how he works. Pay attention to what it does: Output a sentence. note: This Code does not output xml, but only enters a plain text:
Copy codeThe Code is as follows:
<? Php
Header ("Cache-Control: no-cache ");
// Ideally, you 'd put these in a text file or a database.
// Put an entry on each line of 'a.txt 'and use $ prefixes = file ("a.txt ");
// You can do the same with a separate file for $ suffixes.
$ Prefixes = array ('mashup', '2. 0', 'tagging ', 'folksonmy ');
$ Suffixes = array ('web', 'push', 'Media ', 'GU ');
// This selects a random element of each array on the fly
Echo $ prefixes [rand (0, count ($ prefixes)-1)]. "is the new"
. $ Suffixes [rand (0, count ($ prefixes)-1)];
// Example output: Tagging is the new Media
?>
Here, we use the Cache-Control header option because IE always creates a Cache for the same address, even when the page content changes. obviously, this is not good for our example, because we re-generate a sentence each time we load it. we can also use jQuery to generate a random number and add it to the back of the address, but this is not as simple as processing on the server side. [Translator: in fact, the author provides two solutions for conflicts between ajax and IE cache.]
Client code (html)
You can start to write the front-end code, and then we can add ajax. all we need to do is add a button so that users can click to get a new statement and a div tag, so that when we receive the statement from the server, it is displayed in the div. we will use jQuery to select this div and load the returned sentence. We can use the div id to reference it. if necessary, you can load this sentence to different element labels, which may need to use class. but here, we only need to use id. the content in the body tag on this page is:
<Input type = "submit" id = "generate" value = "Generate! ">
<Div id = "quote"> </div>
In general, we need to add a lengthy onSubmit event for this button (that is, the input with the id of generate. sometimes, we use an onSumit event to call a Javascript function. but in jQuery, we do not need to modify any html code. We can simply implement the separation of behavior (event processing) and structure (html code.
Client code (jQuery)
At last we should use jQuery to combine our backend and foreground. as mentioned above, jQuery can be used to select elements from the DOM. first, we should call the ixuanze button and give it an onClick event response. in this event code, we can select the div and load the content. the following is how to write a response to a click event:
$ ("Element expression"). click (function (){
// Code goes here
});
As you may know, when selecting an element in CSS, we use # To use the element id attribute. you can use the same syntax in jQuery. therefore, to select the button, we can use # generate. note that this syntax allows us to define the event processing function as anonymous.
Mark Wubben's JavaScript Terminology page provides a detailed explanation of anonymous functions. For more information, see.
We will use a relatively advanced ajax function in jQuery: load (). Suppose our code is saved as script. php. We will integrate it with our client in this way:
$ ("# Generate"). click (function (){
$ ("# Quote"). load ("script. php ");
});
Only three lines of code are available! Now we have made a complete ajax random statement generator! Good!
The problem is that javascript code is not executed in a function after a browser is loaded. in this way, the code will try to associate an element that may not be loaded. in general, we use window. load to handle this problem, but the limitation of this method is that window. load is loaded only once after all things (images and others) are loaded. we may not be interested in waiting for these images to be loaded-we just need to get the elements in the DOM.
Fortunately, jQuery has a $ (document). ready () function, which is executed after the DOM is loaded.
Complete code
The following is the complete code, using $ (document). ready () and some simple html and css:
Copy codeThe Code is as follows:
<Html>
<Head>
<Title> Ajax with jQuery Example </title>
<Script type = "text/JavaScript" src = "jquery. js"> </script>
<Script type = "text/JavaScript">
$ (Document). ready (function (){
$ ("# Generate"). click (function (){
$ ("# Quote p"). load ("script. php ");
});
});
</Script>
<Style type = "text/css">
# Wrapper {
Width: 240px;
Height: 80px;
Margin: auto;
Padding: 10px;
Margin-top: 10px;
Border: 1px solid black;
Text-align: center;
}
</Style>
</Head>
<Body>
<Div id = "wrapper">
<Div id = "quote"> <p> </div>
<Input type = "submit" id = "generate" value = "Generate! ">
</Div>
</Body>
</Html>
The code can be downloaded here. Note that your jquery file must be saved in the same directory of the PHP file and named jquery. js. now that you are familiar with jQuery, let's do something more complex: form elements and XML processing. This is the real ajax!