JQuery Lesson 5: Ajax

Source: Internet
Author: User

Ajax is no longer a new topic, but jQuery makes ajax extremely simple. JQuery provides several ajax functions. They are similar in that they are separated to process different types of data. The simplest is get (url, parameters, callback). This function initiates a GET request and passes the data returned by the server to callback for processing. In the following example, an ajax request is initiated when the mouse is hovering over the hyperlink, and more about the hyperlink is returned from the server. First look at the server code, create a new ajaxload. ashx, as an example, get the query parameter value of word, and return:

<%@ WebHandler Language="C#" Class="ajaxload" %>using System;using System.Web;public class ajaxload : IHttpHandler {        public void ProcessRequest (HttpContext context) {        context.Response.ContentType = "text/plain";        string word = context.Request.Params["word"];        context.Response.Write(string.Format("<p style='color:red;'>More intorduction of {0} is here....</p>",word));    }     public bool IsReusable {        get {            return false;        }    }}

The front-end code is as follows:

<Head> <title> Ajax Text </title> <script type = "text/javascript" src = "jquery-1.3.2.js"> </script> <script type = "text/javascript"> $ (function () {$ ('A '). hover (function (event) {$. get ('ajaxload. ashx', {word: Functions (event.target).html ()}, function (data) {detail ('{result'}.html (data) ;});}, function () {response ('{result'{.html ("") ;}); </script> 

Move the mouse over Japan and China in sequence. In firebug, we can clearly see that two get requests were initiated. Jquery encodes the parameters and passes them to the server. With the help of jQuery, ajax is so simple.

In this example, the server returns an html clip, which is inserted into the page. In fact, the server returns data in any format, you only need to perform corresponding processing on the front-end. JSON is a commonly used data format. The JSON format itself is not described in this article. Simply put, the JSON format is very similar to the literal volume of objects in javascript. {} Indicates an object, and [] indicates an array.

Below is a three-level linkage drop-down menu. Let's take a look at the final effect:

 

This is a bundle sales product selector. First select the first attribute Game, then select Server, and finally select Amount. How the server finds suitable data from the database and serializes it into JSON data is not the focus of this article. The server can respond to the following requests, and the returned data can also be seen. These are typical JSON formats:

The first request returns the Game list, the second request returns the Server list, and the third request returns a lot of information, in which DisplayName is used to display in the list, ID is the value of the List, and the rest are not used. For example:

<P>

Amount: <select name = "SelectAmount" id = "SelectAmount"> <option value = "45"> 10 Mil </option>

<Option value = "46"> 20 Mil </option> </select>

</P>

The following describes the implementation of the foreground. The HTML code of the drop-down list box is as follows:

<div id="bannerLivechat_content">                <p>                    Game:<select id="SelectGame"></select></p>                <p>                    Server:<select id="SelectServer"></select></p>                <p>                    Amount:<select id="SelectAmount" name="SelectAmount"></select></p>                <p>                    <asp:Button ID="ButtonFasyBuy" CssClass="btn_default" runat="server" Text="BuyNow"                        OnClick="ButtonFasyBuy_Click" />                </p>            </div>

Write the event processing function for the three drop-down lists. First, load the Game list:

Function LoadGame () {$. getJSON ('fastbuy. ashx', function (data) {var sel = $ ('# selectgame') [0]; sel. innerHTML = ""; $. each (data, function (entryIndex, entry) {var op = new Option (entry); sel. options. add (op) ;}); $ ('# selectgame') [0]. selectedIndex = 0; var game = $ ('# selectgame '). val (); LoadServer (game) ;}) ;}first clear the current list, $. the each function can traverse each value in the first parameter and call the function of the second parameter in sequence. And pass the value to the entry parameter. At this time, jQuery has parsed JSON data into javascript objects, which is an array of strings.
Function LoadServer (game) {$. getJSON ('fastbuy. ashx', {Game: game}, function (data) {var sel = $ ('# SelectServer') [0]; sel. innerHTML = ""; $. each (data, function (entryIndex, entry) {var op = new Option (entry); sel. options. add (op) ;}); $ ('# SelectServer') [0]. selectedIndex = 0; LoadAmount (game, $ ('# SelectServer '). val () ;};} the process of loading Server data is similar.
         function LoadAmount(game, server) {             $.getJSON('FastBuy.ashx', {Game:game,Server:server}, function(data) {                 var sel = $('#SelectAmount')[0];                 sel.innerHTML = "";                 $.each(data, function(entryIndex, entry) {                     var op = new Option(entry['AmountAttr'], entry['ID']);                     sel.options.add(op);                 });             });         }

The last step is to load Amount, which is slightly different here. At this time, the data in data is not a simple string, but an attribute object, you can use an expression like entry ['id'] to obtain the expression. In this example, entry ['id'] is a simple number. Of course, it can be another complex object or array, depending on the JSON data returned by the server.

With these preparations, we only need to register the processing function for the drop-down list in the ready function:

$(document).ready(function() {                    $('#SelectServer').change(function() {                LoadAmount($('#SelectGame').val(), $('#SelectServer').val());            });            $('#SelectGame').change(function() {                                 LoadServer($('#SelectGame').val());            });            LoadGame();         });

So far, a three-level linkage drop-down list has been completed.

JQuery also has a $. post function, which is used in the same way as get, but initiates a post request.

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.