HTML+ashx提交表单

将Form表单序列化为数组,然后转换为对象,通过json的方式传到后台。后台将接收到的json反序列化。该方式的优点是直接将Form表单的内容整体打包提交。

HTML代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <script type="text/javascript" src="/scripts/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#form1").submit(function () {
                var formArray = $("#form1").serializeArray();//将form1提交内容序列化为数组
                var formObject = {};
                $.each(formArray, function (index, item) {
                    formObject[item.name] = item.value;
                });//将form1提交的内容转化为对象
                $.post(
                    "/Handler/WebForm_Login.ashx",//响应url
                    { data: JSON.stringify(formObject) },//传递数据
                    function (data, status) {
                        alert("statu:" + status + "\ndata:" + data );//返回状态和数据
                    }
                );
            })
        });
    </script>
    <title>Login</title>
</head>
<body>
    <form id="form1">
        Email:<input type="email" name="email_form1" /><br />
        Name:<input type="text" name="name_form1" />
        <input type="submit" value="Submit" />
    </form>
</body>
</html>

ashx代码: 

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

namespace WebApp.Handler
{
    /// <summary>
    /// Summary description for WebForm_Login
    /// </summary>
    public class WebForm_Login : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string data = context.Request["data"];
            LoginInfo loginInfo = new LoginInfo();
            LoginInfo DeserializeLoginInfo = JsonConvert.DeserializeObject<LoginInfo>(data);//反序列化
            string name = DeserializeLoginInfo.name_form1;
            string email = DeserializeLoginInfo.email_form1;
            string info = "服务区返回数据...\nname:" + name + "\nemail:" + email;
            context.Response.ContentType = "text/plain";
            context.Response.Write(info);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    public class LoginInfo
    {
        public string email_form1 { get; set; }
        public string name_form1 { get; set; }
    }

}

猜你喜欢

转载自blog.csdn.net/u012664198/article/details/88941094