Simple jquery tutorial easy Ajax with jquery full set of Chinese versions page 1/3

Source: Internet
Author: User

Ajax is changing web applications and bringing unprecedented desktop applicationsProgramBeyond the shock. 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 word from Jesse James Garret.Article.

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 it like this.Code:

$ ("Div. foo"). append ("Hello world! ").Css (" color "," Red ");

Easy! In general, this requires two lines of code to complete:

Copy code The 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 code The 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 code The 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> </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!

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.