天天看点

2.jQuery——Ajax用法结合Webform实现简单计算器

简介:表单方式提交比较耗性能、使用Ajax访问服务器后台能很大提高性能、以一个简单的Webform例子为例来进行说明。

1.新建一个空的Webform项目

  1. 在项目中添加Handlers文件夹(用于存放一般处理程序响应ajax请求)和Script(用于存放js文件)文件夹
    2.jQuery——Ajax用法结合Webform实现简单计算器

     一般处理程序的代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Handlers
{
    /// <summary>
    /// Handler 的摘要说明
    /// </summary>
    public class Handler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            int num1 = Convert.ToInt32(context.Request.Params["num1"]);
            int num2 = Convert.ToInt32(context.Request.Params["num2"]);
            int result = num1 + num2;
            context.Response.Write(result.ToString());     
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
           
  1.   在项目中添加一个html页面命名为HtmlPage.html

           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>
    <style type="text/css">
        input {
            width: 70px;
        }
    </style>
    <script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnCal").click(function () {
                $.post("Handlers/Handler.ashx", { "num1": $("#txtNum1").val(), "num2": $("#txtNum2").val() },
                    function (data, status) {
                        if (status == "success") {
                            $("#txtResult").val(data);
                        } else {
                            alert("数据错误!");
                        }
                    });
            });
        });
    </script>
</head>
<body>
    <input id="txtNum1" type="text" />+<input id="txtNum2" type="text" />
    =<input id="txtResult" type="text" />
    <input id="btnCal" type="button" value="计算" />
</body>
</html>
           

2.前端后台交互程序代码说明

①:建立了一般处理程序Handler.ashx之后、html页面中的ajax可以通过"Handlers/Handler.ashx"访问该后台服务。

②:html中Ajax提交的数据“num1”、“num2”。在一般处理程序Handler.ashx中可以通过以下方式获取

  int num1 = Convert.ToInt32(context.Request.Params["num1"]);

  int num2 = Convert.ToInt32(context.Request.Params["num2"]);

③:$.post()的第三个参数是回调函数、一般处理程序通过context.Response.Write(result.ToString());     返回的数据

 可以在第三个参数(函数的第一个形参获取data、第二个参数获取后台程序执行的情况)

3.Ajax程序说明

1).$(function(){}):是页面元素架构加载完之后执行的、一般用于绑定元素的点击事件

2).$.post():post请求方式、第一个参数是url、第二个参数json字符串、第三个参数是回调函数

3)$("#btnCal"):是id选择器、通过id选择元素

4) $("#txtNum1").val():获取元素的值

5). $("#txtResult").val(data):给指定的元素赋值

如果错误之处请指正、谢谢!

本博客仅做学习记录之用、如有侵权联系删除。

可以通过邮箱给我反馈[email protected]

继续阅读