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 19 <input type="button" name="btnSubmit" id="btnSubmit" value=" 计 算 " /> 20 21 </div> 22 </form> 23 </body> 24 </html>
2.好习惯,新建一个js文件: js/common.js
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
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返回两个数字的和,输入中文的没反应的属正常现象.
图一