微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【Asp.net】 Ajax小例子

ajax的作用是用来进行异步http请求,获取远程数据。在实践中,能学到好多。这不在实践中把ajax给理解了一些。积累了两种Asp.net程序使用ajax的方式。

1、通过一般处理程序.ashx

vs目录如下图:


(1)新建个web页面(.aspx),写一个简单的html页面

<form id="form1" runat="server" method="post">
        <div >
            <div id="prompt"></div>
            <div>
                <label>账号</label>
                <input type="text" id="personalnewphone" value="15712345678" placeholder="邮箱/手机号" runat="server" />
                <button type="button" id="FqAuthcode" runat="server" >
                    获取验证码
                </button>
            </div>
        </div>
    </form>

(2)引入jquery文件,写ajax传值方法

<script src="../js/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            //获取验证码
            $("#FqAuthcode").bind("click",function () {

                var _loginname = $("#personalnewphone").val();

                if (_loginname == '') {
                    $('#prompt').removeClass('hidden').addClass('text-danger').html('手机或邮箱不能为空');
                    return false;
                }
                $.post("../ajax/Getcode.ashx",{ action: 'register',loginname: _loginname },function (data) {
                    if (data.code == 10000) {
                        $("#sub-btn-Box").removeClass('hidden');
                        $(".personalcode").css("display","block");
                        $('#prompt').removeClass('hidden').addClass('text-danger').html(data.message);
                    } else {
                        $('#prompt').removeClass('hidden').addClass('text-danger').html(data.message);
                    }
                    console.log(data.message);
                },'json');
            });

	    });
    </script>


$post方法与$get方法是在jquery中高层实现常用的。post与get方法的区别跟字面意思的区别一样。post是向指定的资源提交要处理的数据。get是从指定的资源请求数据。例子中的业务需求是,把手机号提交到后台,进行存在性验证,以及给该手机号发验证码等处理。需要把页面中的手机号提交,因此用post方法

例子中的需求还可以通过jquery底层ajax实现。


$.ajax({
                    url: "../ajax/Getcode.ashx",async:false,data:{ action: 'register',success: function (data) {
                        if (data.code == 10000) {
                            $("#sub-btn-Box").removeClass('hidden');
                            $(".personalcode").css("display","block");
                            $('#prompt').removeClass('hidden').addClass('text-danger').html(data.message);
                        } else {
                            $('#prompt').removeClass('hidden').addClass('text-danger').html(data.message);
                        }
                    },dataType: "json"
                });



(3)新建一个一般处理程序,接收通过ajax方法传过来的值,进行处理,然后返回ajax方法


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

namespace Asp.net_Ajax_Demo1.ajax
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            context.Response.ContentType = "text/html;charset=utf-8";
            //获取传过来的参数
            string action = context.Request.Params["action"]; //方法名称
            string loginname = context.Request.Params["loginname"]; //要重置密码的账号


            //调用函数
            string json = GetJsonStr(action,loginname);
            context.Response.Write(json);//返回处理结果
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string GetJsonStr(string action,string loginname) {
            StringBuilder jsonString = new StringBuilder();
            switch (action)
            {
                case "register"://注册发送验证码
                    //Todo:发送验证码方法省略

                    jsonString.Append("{\"code\":\"10000\",\"message\":\"验证码发送成功\"}");
                    break;
                default:
                    jsonString.Append("{\"code\":\"1\",\"message\":\"未知错误,请联系管理员\"}");
                    break;
            }

            return jsonString.ToString();

        }
    }
}

之所以用switch判断,是为了用同一个一般处理程序(Handler)处理多个ajax请求。如果不用switch判断的话,就要建立多个Handler。


效果如图所示:


2、不通过一般处理程序.aspx

目录结构如图:

(1)新建webservice页面(.asmx)。取消注释行,使用web服务

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

namespace WebApplication1.web
{
    /// <summary>
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolBoxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public string GetCode(string loginname)
        {
            StringBuilder jsonString = new StringBuilder();
            
            //Todo:发送验证码方法省略
            jsonString.Append("{\"code\":\"10000\",\"message\":\"验证码发送成功\"}");
            return jsonString.ToString();
        }
    }
}



(2)新建web页面(.aspx)。添加页面基本元素及布局。添加ScriptManager,用来相应webservice

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.web.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<Meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>ajax_demo2</title>
</head>
<body>
    <form id="form1" runat="server">

        <%--响应webservice--%>
        <asp:ScriptManager ID="clientService" runat="server">
            <Services>
                <asp:ServiceReference Path="~/web/WebService1.asmx" /><%--webservice路径--%>
            </Services>
        </asp:ScriptManager>


        <div >
            <div id="prompt"></div>
            <div>
                <label>账号</label>
                <input type="text" id="personalnewphone" value="15712345678" placeholder="邮箱/手机号" runat="server" />
                <button type="button" id="FqAuthcode" runat="server" >
                    获取验证码
                </button>
            </div>
        </div>
    </form> 

</body>
</html>



(3)引用jquery文档,js编写

<script src="../js/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            //获取验证码
            $("#FqAuthcode").bind("click",function () {


                var _loginname = $("#personalnewphone").val();

                if (_loginname == '') {
                    $('#prompt').removeClass('hidden').addClass('text-danger').html('手机或邮箱不能为空');
                    return false;
                }

               
                //webservice方法
                //要调用方法的完整路径,WebService命名空间.WebService类名.方法名
                WebApplication1.web.WebService1.GetCode(_loginname,function (data) {
                    //响应成功

                    var json=$.parseJSON(data);//把字符串转成json格式
                    if (json.code == 10000) {
                        $("#sub-btn-Box").removeClass('hidden');
                        $(".personalcode").css("display","block");
                        $('#prompt').removeClass('hidden').addClass('text-danger').html(json.message);
                    } else {
                        $('#prompt').removeClass('hidden').addClass('text-danger').html(json.message);
                    }

                },function () {
                    //响应失败
                    setContainer('Error!');
                });


            });

        });
    </script>

效果如图:


对比:

jQuery调用Handler几乎完美了,但是不能处理多个方法用webService和ScriptManager,可以调用多个方法

总结:

有了理论要在实践中去验证,验证过了还要总结成理论。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐