C# Ajax 返回json数据

本文详细介绍了前端通过AJAX调用后台实现登录验证的过程,包括使用$.ajax方法发送POST请求,以及后台如何处理这些请求并返回JSON格式的响应信息。文章还特别强调了使用Newtonsoft.Json.dll进行JSON数据转换的重要性。

前台调用

function checkLogin() {

        var name = $("#email").val();
        var passward = $("#password").val();

        $.ajax({
            url: 'Ajax/web.ashx?method=login',
            type: 'POST',
            data: { "name": name, "passward": passward },
            //type=1位撤销
            dataType: 'json',
            success: function (dataInfo) {

                alert(dataInfo.IsSuccess);

            },
            async: false
        });

    }

后台 ajax

JsonConvert的使用需要添加引用Newtonsoft.Json.dll

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using Putty.Common;
using Newtonsoft.Json;

namespace WebFrameDemo.web.Ajax
{
    /// <summary>
    /// web 的摘要说明
    /// </summary>
    public class web : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string strMethod = context.Request["method"];

            if (!string.IsNullOrEmpty(strMethod))
            {
                switch (strMethod)
                {
                    case "login":
                        GetLogin(context);
                        break;
                    


                }
            }
        }
        private void GetLogin(HttpContext context)
        {


            string _name = context.Request["name"];
            string _password = context.Request["_password"];

            CommonModel.resultMsg msg = new CommonModel.resultMsg();
            msg.IsSuccess = false;
            msg.Info = "失败";

            context.Response.Write(JsonConvert.SerializeObject(msg));

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

JsonConvert.SerializeObject也可以传List<T>等数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值