一个jquery ajax例子

上次搞了个jquery的AutoComplete效果,感觉很久没写jquery了,趁热打铁,再找点东西练练手.这不,看了一下jquery手册,顺便写了一个小例子,源码我直接贴上来了.
 
1.新建一个web窗体:index.aspx
 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %>
 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 3 <html xmlns="http://www.w3.org/1999/xhtml">
 4 <head runat="server">
 5     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 6     <title>Ajax Test Page</title>
 7     <script src="js/jquery-1.6.js" type="text/javascript"></script>
 8  <script src="js/common.js" type="text/javascript"></script>
 9 </head>
10 <body>
11     <form id="form1" runat="server">
12     <div>
13     
14         <asp:TextBox ID="txtNumA" runat="server" Width="50px"></asp:TextBox>
15         +<asp:TextBox ID="txtNumB" runat="server" Width="50px"></asp:TextBox>
16         =<asp:TextBox ID="txtSums" runat="server" Width="50px"></asp:TextBox>
17     
18     &nbsp;
19         <input type="button" name="btnSubmit" id="btnSubmit" value=" 计 算 " />
20     
21     </div>
22     </form>
23 </body>
24 </html>

 

2.好习惯,新建一个js文件: js/common.js

说明:这里,简单说一下$.get()的使用方法,jquery手册上面有它的基本语法,这里面注意一下function(data){...}这个Callback的参数data就可以了,data代表的是处理页面(这里是Ajax/Count.ashx)发送回来的文本(格式有多种,我还没深入了解),至于怎么发送,看看处理页面的代码,下面会说.
 1 $(document).ready(function() {
 2     $("#btnSubmit").click(function() {
 3         if (($.trim($("#txtNumA").val()) == "") || ($.trim($("#txtNumB").val()) == "")) {
 4             alert("請輸入完整的信息");
 5             return false;
 6         }
 7         $.get("Ajax/Count.ashx", { a: $("#txtNumA").val(), b: $("#txtNumB").val() },
 8     function(data) {
 9         $("#txtSums").attr("value", data);
10         //alert("nums:" + data);
11     });
12     });
13 });

 
3.最后,新建一个处理页面:Ajax/Count.ashx

说明:页面处理完传过来的数据之后,怎么把数据传回去呢?在asp和asp.net中都是以Response.Write的形式返回结果,而像PHP则是echo.同时,请求页面那里的回调函数就会接到一个数值(一般function(data){...}中的data就代表这个处理页面Response.Write的结果了),如果想知道jquery是怎么样获取到这个数值的,可以回到第二点看仔细点.
另外,返回值要写在ProcessRequest(..){//code}的方法内,代码如下:
 1 <%@ WebHandler Language="C#" class="Count" %>
 2 using System;
 3 using System.Web;
 4 public class Count : IHttpHandler {
 5     
 6     public void ProcessRequest (HttpContext context) {
 7         context.Response.ContentType = "text/plain";
 8         int a = Convert.ToInt32(context.Request.QueryString["a"].Trim());
 9         int b = Convert.ToInt32(context.Request.QueryString["b"].Trim());
10         context.Response.Write(GetCounts(a, b));
11     }
12     private int GetCounts(int x, int y)
13     {
14         return x + y;
15     }
16  
17     public bool IsReusable {
18         get {
19             return false;
20         }
21     }
22 }

 

4.自己上网下载一个jquery.js,下图为此项目的文件目录,此项目的功能就是利用AJAX返回两个数字的和,输入中文的没反应的属正常现象.

图一

posted @ 2012-06-28 16:41  Seasons1987  阅读(822)  评论(0编辑  收藏  举报