More simple jquery tutorials easy Ajax with jquery Chinese version 1th/3 page _jquery

Source: Internet
Author: User
Tags anonymous php file rand require wrapper

Ajax is changing web apps and bringing an unprecedented shock to desktop applications. But behind the hype, we should be aware that Ajax is just--(X) Html,javascript and XML--nothing new. In this tutorial, I'll show you how to simply add Ajax to your application, and teach you how to use a popular JavaScript library Jquey for AJAX development.

1. What is Ajax

You've probably heard of Ajax before, or at least used Ajax apps-like Gmail. Simply put, Ajax uses JavaScript to process data asynchronously, rather than overloading the entire page. There's a tutorial on SitePoint a good introduction to Ajax. In addition, the word Ajax is derived from the famous article by Jesse James Garrett.

Unfortunately, the in-depth hands-on tutorials on Ajax can be said to be few and far between, and the XMLHttpRequest class used in Ajax has a lot of difficulty for beginners. But thankfully, there are a large number of JavaScript libraries that appear in succession, Provides a simple way to implement Ajax. The jquery we're going to use today is one of them.

2. What is jquery

jquery is a mature JavaScript library that provides features that many other libraries do not have. Admittedly, it has a 19K of size, and does not want to moo.fx that only 3KB light. You can see the comparison data for many JavaScript library performance and other aspects here.

3. Prior knowledge

To learn this tutorial, you need to have basic JavaScript just, if you know the C-style language, then you can quickly get started with JavaScript. In fact, it's just curly braces, function declarations, and optional end-line semicolons (for jquery; must). If you want to learn JavaScript, you can look at this tutorial. Also, since we're talking about Web apps, basic HTML is just natural and essential.

4. Jquery 101

Let's take a quick look at jquery. To use jquery, you first have to download the library. This is the 1.1.2 (current version). jquery's syntax is very simple: find it and do it. We use $ () for selecting elements from the document. This symbol is equivalent to document.getElementById (), but in addition to supporting IDs, it also supports CSS selectors and some XPath selectors. Also, it can return an array of elements. Well, perhaps an example would be a better description of the $ () function.

We want to use functions to manipulate our selectors. For example, to add "Hello world!" to each div of class Foo, and then set the color to red, we can write code like this:

$ ("Div.foo"). Append ("Hello world!"). CSS ("Color", "red");

It's simple! In general, this requires two lines of code to complete:

Copy Code code as follows:

$ ("Div.foo"). Append ("Hello world!");
$ ("Div.foo"). CSS ("Color", "red");

jquery's link method can be to allow you to ligatures your code, which other libraries I am afraid not. There are many jquery functions that do not require objects, that is, work independently, and many AJAX-related functions do so. For example, we will use the post function, called by the $.post ( Parameters). More jquery function information can come online documentation or visualjquery.com.

5. Example one: Our first AJAX program

As an example, we'll do an interactive concept builder. To put it simply, let's randomly select two options from the list and then combine them into a single phrase. In this example we will use the words web2.0 features (such as ' mashups ', ' folksonomy ', ' Media ', and so on), Usually we get these options from a text file. To save time for users to download each combination (or at least every element) in JavaScript, we will quickly generate it on the server side, and use jquery to get it on the client. jquery works well with JavaScript, so you'll find that using it in your code makes it easy to work.

Server-side code (PHP):
For simplicity, we use the simplest code to do our concept builder. Don't worry about how he works, pay attention to what it does: output a sentence. Note that this code does not output XML, he simply enters a plain text:

Copy Code code as follows:

<?php
Header ("Cache-control:no-cache");
Ideally, you ' d be put here in a text file or a database.
Put a entry on the ' A.txt ' and use $prefixes = File ("A.txt");
You can do the same and a separate file for $suffixes.
$prefixes = Array (' Mashup ', ' 2.0 ', ' Tagging ', ' folksonomy ');
$suffixes = Array (' Web ', ' Push ', ' Media ', ' GUI ');
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 content of the page changes. Obviously, this is bad for our example, Because we regenerate a sentence each time we load. We can also use jquery to generate a random number to add to the back of the address, but this is not as simple as on the server side. In fact, the author offers two solutions for Ajax and IE cache conflicts.

client code (HTML)

You can start writing the front-end code, and then we can add Ajax to it. All we need to do is add a button so the user clicks on a new statement and a DIV tag, So that we can get the statements from the server side to display in the Div. We'll use jquery to select this div and load the returned sentence, and we could use the Div ID to refer to it. If you need to, you can load this sentence into different element tags, This may require class. But here, we just need to use IDs. The contents of the body tag for this page are:

<input type= "Submit" id= "Generate" value= "generate!" >
<div id= "Quote" ></div>

In general, we need to add a lengthy onsubmit event to this button (that is, the input for this ID is generate). Sometimes we call a JavaScript function with the Onsumit event. But in jquery, we set up no need to modify any HTML code, we can simply implement the behavior (event handling) and structure (HTML code) separation.

Client code (JQUERY)

It's time to use jquery to get our backstage and front desk together. I mentioned earlier that we can use jquery to select elements from the DOM. First, we should ixuanze this button and give it a onclick event response. In this event code, We can select the div and load the contents. The following is the wording of the Click event Response:

$ ("element expression"). Click (function () {
Code goes here
});

Perhaps you already know that we use # to use the id attribute of an element when selecting an element in CSS. You can use the same syntax in jquery. So, to select that button, we can use #generate. Note that this syntax allows us to define the event handler function as anonymous.

Mark Wubben's JavaScript Terminology page provides detailed explanations of anonymous functions that are interesting to refer to.

We're going to use a more advanced Ajax function in jquery: Load (). Let's say our code is saved as script.php. So we combine it with our clients:

$ ("#generate"). Click (function () {
$ ("#quote"). Load ("script.php");
});

Only: 3 lines of code! Now we've done a complete AJAX random statement generator!

The problem is that JavaScript code is not inside a function that executes when a browser is loaded. In this case, this code will attempt to correlate an element that may not have been loaded yet. In general, we use Window.load to deal with this problem, but the limitation of this approach is that Window.load is loaded once after all the things (pictures and others) have been loaded. We may have no interest in waiting for these images to load-we just need to get the elements in the DOM.

Luckily, jquery has a $ (document). Ready () function, such as its name, is executed after the DOM has been loaded.

The complete code

Here is the complete code, using $ (document). Ready () and some simple HTML and CSS:

Copy Code code as follows:

<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>
<body>
<div id= "wrapper" >
<div id= "quote" ><p> </p></div>
<input type= "Submit" id= "Generate" value= "generate!" >
</div>
</body>


The code can be downloaded here, and note that your jquery needs to be saved in the same directory as the PHP file, and named Jquery.js. Now that you're familiar with jquery, let's do something more complicated: form elements and XML processing, which is the real ajax!
Current 1/3 page 123 Next read the full text
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.