当前位置:Gxlcms > JavaScript > ASP.NET使用Ajax如何返回Json对象的示例方法介绍

ASP.NET使用Ajax如何返回Json对象的示例方法介绍

时间:2021-07-01 10:21:17 帮助过:71人阅读

这篇文章主要介绍了ASP.NET使用Ajax返回Json对象的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下

一、新建一个html页面,如注册页面"Register.htm"

二、新建一js文件,如:reg.js

三、处理ajax请求

方法一:手动拼接json字符串

新建一般处理程序,如:Register.ashx

using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
namespace WebLogin
{
  /// <summary>
  /// $codebehindclassname$ 的摘要说明
  /// </summary>
  [WebService(Namespace = "http://tempuri.org/")]
  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  public class Register1 : IHttpHandler
  {
    public void ProcessRequest(HttpContext context)
    {
      context.Response.ContentType = "application/json";//设置响应内容的格式是json格式
      string id = context.Request["id"];
      string pwd = context.Request["pwd"];
      string name = context.Request["name"];
      List<string> msgList = new List<string>();
      if (String.IsNullOrEmpty(id))
      {
        msgList.Add("{\"id\":\"idMsg\",\"message\":\"用户名不能为空.\"}");
      }
      if (pwd==null || pwd=="")
      {
        msgList.Add("{\"id\":\"pwdMsg\",\"message\":\"密码不能为空.\"}");//形如:{"id":"pwdMsg","message":"密码不能为空."}
      }
      if (name==null || name=="")
      {
        msgList.Add("{\"id\":\"nameMsg\",\"message\":\"姓名不能为空.\"}");
      }
      string responseText = "";
      if (msgList.Count == 0)
      {
        //调用后台代码写入数据库
        responseText = "{\"success\":true,\"message\":\"注册成功\"}";
      }
      else
      {
        string msgsValue = "";
        for (int i = 0; i < msgList.Count; i++)
        {
          msgsValue += msgList[i] + ",";//将列表中的每一个字符串连接起来,用","隔开,不过最后还会多","
        }
        msgsValue=msgsValue.Substring(0, msgsValue.Length - 1);//去掉末尾的","
        msgsValue = "[" + msgsValue + "]";//用"[]"括起来,如:[{"id":"pwdMsg","message":"密码不能为空."},{"id":"nameMsg","message":"姓名不能为空."}]
        responseText = "{\"success\":false,\"message\":\"注册失败\",\"msgs\":" + msgsValue + "}";
        //最的形如:{"success":false,"message":"注册失败","msgs":[{"id":"pwdMsg","message":"密码不能为空."},{"id":"nameMsg","message":"姓名不能为空."}]}
      }
      context.Response.Write(responseText);
    }
    public bool IsReusable
    {
      get
      {
        return false;
      }
    }
  }
}

方法二:使用Json.NET工具来将C#对象转换json输出

1、新建信息类“Msg.cs”

2、新建返回json对象的类“ResponseData.cs”

3、去官网下载Json.NET,并复制引用

下载解压后将“Newtonsoft.Json.dll”复制到项目的“bin”目录中,并引用(注意和.net版本保持一致)

4、新建一般处理程序“reg.ashx”

四、完成效果如图

以上就是ASP.NET使用Ajax如何返回Json对象的示例方法介绍的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行