随笔- 292  评论- 3614  文章- 47 

Ajax简单实例----无刷新求和运算

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SumNumber.aspx.cs" Inherits="SumNumber" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无刷新求和示例</title>
<script type="text/javascript">
    var xmlHttp;
    function createXMLHttpRequest()
    {
        if(window.ActiveXObject)
        {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else if(window.XMLHttpRequest)
        {
            xmlHttp = new XMLHttpRequest();
        }
    }
    //处理方法
    function AddNumber()
    {
        createXMLHttpRequest();
        var url= "Handler.ashx?num1="+document.getElementById("num1").value+"&num2="+document.getElementById("num2").value;
        xmlHttp.open("GET",url,true);
        xmlHttp.onreadystatechange=ShowResult;
        xmlHttp.send(null);
    }
    //回调方法
    function ShowResult()
    {
        if(xmlHttp.readyState==4)
        {
            if(xmlHttp.status==200)
            {
                document.getElementById("sum").value=xmlHttp.responseText;
            }
        }
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="text-align: center">
        <br />无刷新加法运算简单示例<br />
        <br />
        <input id="num1" style="width: 107px" type="text" onkeyup="AddNumber();" value="0"  />
        +<input id="num2" style="width: 95px" type="text"  onkeyup="AddNumber();" value="0"  />
        =<input id="sum" style="width: 97px" type="text" /></div>
    </form>
</body>
</html>

这个实例中还用到了程序处理文件,代码如下:
<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;

public class Handler : IHttpHandler
{
   
    public void ProcessRequest (HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        int result = Convert.ToInt32(context.Request.QueryString["num1"]) + Convert.ToInt32(context.Request.QueryString["num2"]);
        context.Response.Write(result);
    }
 
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

posted on 2007-08-05 14:25  Bēniaǒ  阅读(...)  评论(... 编辑 收藏