Simple Ajax and ASP.NET Example

HtmlPage.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>无标题页</title>

    <script type="text/javascript">
        var ajaxRequest;
        function initAJAX() {
            try {
                ajaxRequest = new XMLHttpRequest();
            }
            catch (error) {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        function handleInput() {
            var T1 = document.getElementById("Text1");
            var T2 = document.getElementById("Text2");
            var theURL = "MultiplyAJAXServer.aspx?nx=" + T1.value + "&ny=" + T2.value;

            ajaxRequest.open("GET", theURL);
            ajaxRequest.onreadystatechange = handleUpdate;
            ajaxRequest.send();
        }
        function handleUpdate() {
            //alert(ajaxRequest.readyState);
            var ansDiv = document.getElementById("ans");
            if (ajaxRequest.readyState == 4) {
                ansDiv.innerHTML = ajaxRequest.responseText;
            }
        }
    </script>

</head>
<body onload="initAJAX();">
    <div>
        First &nbsp; &nbsp; &nbsp;<input id="Text1" type="text" onkeyup="handleInput();" /><br />
    </div>
    <div>
        Second
        <input id="Text2" type="text" onkeyup="handleInput();" /><br />
        <br />
    </div>
    <div id="ans">
        Answer</div>
</body>
</html>


MultiplyAJAXServer.aspx 

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    </form>
</body>
</html>


MultiplyAJAXServer.aspx.cs 

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class MultiplyAJAXServer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int nX = 0;
        int nY = 0;
        try
        {
            nX = Convert.ToInt32(Request.QueryString["nx"]);
            nY = Convert.ToInt32(Request.QueryString["ny"]);
        }
        catch (Exception ex)
        {
            nX = 0;
            nY = 0;
        }
        int nAns = nX * nY;
        Response.Write(nAns);
    }
}

posted on 2008-07-18 16:48  NullReferenceException  阅读(183)  评论(0)    收藏  举报