ASP.Net使用AJAX返回Json对象

 

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

 
  1. <!DOCTYPE html>

  2. <html >

  3. <head>

  4. <title>用户注册</title>

  5. <meta charset="utf-8" />

  6. <style type="text/css">

  7. .msg

  8. {

  9. color:Red;

  10. }

  11. </style>

  12. </head>

  13. <body>

  14. <!--

  15. 因为是ajax提交,html表单控件可以不必放在form里,且不能使用提交按纽(type="submit"),而使用普通按纽(type="button")

  16. -->

  17. 用户名:<input type="text" name="id" id="id" /><span id="idMsg" class="msg"></span><br /> <!-- span用来显示错误信息 -->

  18. 密 码:<input type="password" name="pwd" id="pwd" /><span id="pwdMsg" class="msg"></span><br />

  19. 姓 名:<input type="text" name="name" id="xm" /><span id="nameMsg" class="msg"></span><br />

  20. <input id="btnReg" type="button" value="注册" />

  21. <script type="text/javascript" src="bootstrap/js/jquery.js">

  22. </script>

  23. <script src="reg.js" type="text/javascript"></script>

  24. </body>

  25. </html>

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

 
  1. $(function() {

  2. //定义清除错误信息的函数

  3. function clearMsg() {

  4. $(".msg").html("");

  5. }

  6.  
  7. //定义获取表单数据的函数,注意返回json对象

  8. function formData() {

  9. return {

  10. id: $("#id").val(),

  11. pwd: $("#pwd").val(),

  12. name: $("#xm").val()

  13. };

  14. }

  15.  
  16. //定义注册功能的函数

  17. function reg() {

  18. var url = "Register.ashx";

  19. var data = formData();

  20. clearMsg();

  21. $.ajax({

  22. type: 'GET', //自动会把json对象转换为查询字符串附在url后面如:http://localhost:49521/Register.ashx?id=a&pwd=b&name=c

  23. url: url,

  24. dataType: 'json', //要求服务器返回一个json类型的数据,如:{"success":true,"message":"注册成功"}

  25. contentType: 'application/json',//发送信息给服务器时,内容编码的类型

  26. data: data, //提交给服务器的数据,直接使用json对象的数据,如:{"id":"a","pwd":"b","name":"c"} (如果要求json格式的字符串,可使用用JSON.stringify(data))

  27. success: function(responseData) {//如果响应成功(即200)

  28. if (responseData.success == true) {//responseData也是json格式,如:{"success":true,"message":"注册成功"}

  29. alert(responseData.message);

  30. } else {

  31. var msgs = responseData.msgs;//msgs对象是一个数组,如下所示:

  32. //{"success":false,"message":"注册失败","msgs":[{"id":"pwdMsg","message":"密码不能为空."},{"id":"nameMsg","message":"姓名不能为空."}]}

  33. for (var i = 0; i < msgs.length; i++) {

  34. $('#' + msgs[i].id).html(msgs[i].message);

  35. }

  36. }

  37. },

  38. error: function() {

  39. //要求为Function类型的参数,请求失败时被调用的函数。该函数有3个参数,即XMLHttpRequest对象、错误信息、捕获的错误对象(可选)。ajax事件函数如下:

  40. //function(XMLHttpRequest, textStatus, errorThrown){

  41. //通常情况下textStatus和errorThrown只有其中一个包含信息

  42. //this; //调用本次ajax请求时传递的options参数

  43. alert(arguments[1]);

  44. }

  45. });//ajax

  46. }

  47.  
  48. //定义一个初始化函数

  49. function init() {

  50. $("#btnReg").click(function() {

  51. reg();

  52. });

  53. }

  54.  
  55. //调用初始化函数

  56. init();

  57. });

 

三、处理ajax请求

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

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

 
  1. using System;

  2. using System.Collections;

  3. using System.Data;

  4. using System.Linq;

  5. using System.Web;

  6. using System.Web.Services;

  7. using System.Web.Services.Protocols;

  8. using System.Xml.Linq;

  9. using System.Collections.Generic;

  10.  
  11. namespace WebLogin

  12. {

  13. /// <summary>

  14. /// $codebehindclassname$ 的摘要说明

  15. /// </summary>

  16. [WebService(Namespace = "http://tempuri.org/")]

  17. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

  18. public class Register1 : IHttpHandler

  19. {

  20.  
  21. public void ProcessRequest(HttpContext context)

  22. {

  23. context.Response.ContentType = "application/json";//设置响应内容的格式是json格式

  24. string id = context.Request["id"];

  25. string pwd = context.Request["pwd"];

  26. string name = context.Request["name"];

  27. List<string> msgList = new List<string>();

  28. if (String.IsNullOrEmpty(id))

  29. {

  30. msgList.Add("{\"id\":\"idMsg\",\"message\":\"用户名不能为空.\"}");

  31. }

  32. if (pwd==null || pwd=="")

  33. {

  34. msgList.Add("{\"id\":\"pwdMsg\",\"message\":\"密码不能为空.\"}");//形如:{"id":"pwdMsg","message":"密码不能为空."}

  35. }

  36. if (name==null || name=="")

  37. {

  38. msgList.Add("{\"id\":\"nameMsg\",\"message\":\"姓名不能为空.\"}");

  39. }

  40.  
  41.  
  42. string responseText = "";

  43. if (msgList.Count == 0)

  44. {

  45. //调用后台代码写入数据库

  46. responseText = "{\"success\":true,\"message\":\"注册成功\"}";

  47. }

  48. else

  49. {

  50. string msgsValue = "";

  51. for (int i = 0; i < msgList.Count; i++)

  52. {

  53. msgsValue += msgList[i] + ",";//将列表中的每一个字符串连接起来,用","隔开,不过最后还会多","

  54. }

  55. msgsValue=msgsValue.Substring(0, msgsValue.Length - 1);//去掉末尾的","

  56. msgsValue = "[" + msgsValue + "]";//用"[]"括起来,如:[{"id":"pwdMsg","message":"密码不能为空."},{"id":"nameMsg","message":"姓名不能为空."}]

  57. responseText = "{\"success\":false,\"message\":\"注册失败\",\"msgs\":" + msgsValue + "}";

  58. //最的形如:{"success":false,"message":"注册失败","msgs":[{"id":"pwdMsg","message":"密码不能为空."},{"id":"nameMsg","message":"姓名不能为空."}]}

  59. }

  60. context.Response.Write(responseText);

  61. }

  62.  
  63. public bool IsReusable

  64. {

  65. get

  66. {

  67. return false;

  68. }

  69. }

  70. }

  71. }

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

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

 
  1. using System;

  2. using System.Data;

  3. using System.Configuration;

  4. using System.Linq;

  5. using System.Web;

  6. using System.Web.Security;

  7. using System.Web.UI;

  8. using System.Web.UI.HtmlControls;

  9. using System.Web.UI.WebControls;

  10. using System.Web.UI.WebControls.WebParts;

  11. using System.Xml.Linq;

  12.  
  13. namespace WebLogin

  14. {

  15. public class Msg

  16. {

  17. private string id;

  18.  
  19. public string Id

  20. {

  21. get { return id; }

  22. set { id = value; }

  23. }

  24. private string message;

  25.  
  26. public string Message

  27. {

  28. get { return message; }

  29. set { message = value; }

  30. }

  31. public Msg(string id, string message)

  32. {

  33. this.id = id;

  34. this.message = message;

  35. }

  36. }

  37. }

复制代码

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

复制代码

 
  1. using System;

  2. using System.Data;

  3. using System.Configuration;

  4. using System.Linq;

  5. using System.Web;

  6. using System.Web.Security;

  7. using System.Web.UI;

  8. using System.Web.UI.HtmlControls;

  9. using System.Web.UI.WebControls;

  10. using System.Web.UI.WebControls.WebParts;

  11. using System.Xml.Linq;

  12. using System.Collections.Generic;

  13.  
  14. namespace WebLogin

  15. {

  16. public class ResponseData

  17. {

  18. private bool success;

  19.  
  20. public bool Success

  21. {

  22. get { return success; }

  23. set { success = value; }

  24. }

  25. private string message;

  26.  
  27. public string Message

  28. {

  29. get { return message; }

  30. set { message = value; }

  31. }

  32. private List<Msg> msgs;

  33.  
  34. public List<Msg> Msgs

  35. {

  36. get { return msgs; }

  37. set { msgs = value; }

  38. }

  39.  
  40. public ResponseData(bool success, string message)

  41. {

  42. this.success = success;

  43. this.message = message;

  44. }

  45. public ResponseData(bool success, string message, List<Msg> msgs)

  46. {

  47. this.success = success;

  48. this.message = message;

  49. this.msgs = msgs;

  50. }

  51. }

  52. }

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

官网:http://www.newtonsoft.com/json

下载地址:http://pan.baidu.com/s/1nvz9JBV

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

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

 
  1. using System;

  2. using System.Collections;

  3. using System.Data;

  4. using System.Linq;

  5. using System.Web;

  6. using System.Web.Services;

  7. using System.Web.Services.Protocols;

  8. using System.Xml.Linq;

  9. using System.Collections.Generic;

  10.  
  11. using Newtonsoft.Json;//引入

  12.  
  13. namespace WebLogin

  14. {

  15. /// <summary>

  16. /// $codebehindclassname$ 的摘要说明

  17. /// </summary>

  18. [WebService(Namespace = "http://tempuri.org/")]

  19. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

  20. public class reg : IHttpHandler

  21. {

  22.  
  23. public void ProcessRequest(HttpContext context)

  24. {

  25. context.Response.ContentType = "application/json";//设置响应内容的格式是json格式

  26. string id = context.Request["id"];

  27. string pwd = context.Request["pwd"];

  28. string name = context.Request["name"];

  29. List<Msg> msgs = new List<Msg>();

  30. if (String.IsNullOrEmpty(id))

  31. {

  32. msgs.Add(new Msg("idMsg", "用户名不能为空."));

  33. }

  34. if (String.IsNullOrEmpty(pwd))

  35. {

  36. msgs.Add(new Msg("pwdMsg", "密码不能为空."));

  37. }

  38. if (String.IsNullOrEmpty(name))

  39. {

  40. msgs.Add(new Msg("nameMsg", "姓名不能为空."));

  41. }

  42.  
  43. ResponseData rData;

  44. if (msgs.Count == 0)

  45. {

  46. //调用注册方法,写入数据库

  47. rData = new ResponseData(true, "注册成功.");

  48. }

  49. else

  50. {

  51. rData = new ResponseData(false, "注册失败.", msgs);

  52. }

  53.  
  54. context.Response.Write(JsonConvert.SerializeObject(rData));//直接调用方法将rData转换为json字符串

  55. }

  56.  
  57. public bool IsReusable

  58. {

  59. get

  60. {

  61. return false;

  62. }

  63. }

  64. }

  65. }

四、完成效果如图

ajax技术,无刷新技术 导读:ScriptManager控件包括在ASP.NET 2.0 AJAX Extensions,它用来处理页面上的所有组件以及页面局部更新,生成相关的客户端代理脚本以便能够在JavaScript访问Web Service,所有需要支持ASP.NET AJAXASP.NET页面上有且只能有一个ScriptManager控件。在ScriptManager控件我们可以指定需要的脚本库,或者指定通过JS来调用的Web Service,以及调用AuthenticationService和ProfileService,还有页面错误处理等。 ASP.NET AJAX入门系列(3):使用ScriptManagerProxy控件 导读:在ASP.NET AJAX,由于一个ASPX页面上只能有一个ScriptManager控件,所以在有母版页的情况下,如果需要在Master-Page和Content-Page需要引入不同的脚本时,这就需要在Content-page使用ScriptManagerProxy,而不是ScriptManager,ScriptManager 和 ScriptManagerProxy 是两个非常相似的控件。 ASP.NET AJAX入门系列(4):使用UpdatePanel控件(一) 导读:UpdatePanel可以用来创建丰富的局部更新Web应用程序,它是ASP.NET 2.0 AJAX Extensions很重要的一个控件,其强大之处在于不用编写任何客户端脚本,只要在一个页面上添加几个UpdatePanel控件和一个ScriptManager控件就可以自动实现局部更新。通过本文来学习一下UpdatePanel简单的使用方法(第一篇)。 ASP.NET AJAX入门系列(5):使用UpdatePanel控件(二) 导读:UpdatePanel可以用来创建丰富的局部更新Web应用程序,它是ASP.NET 2.0 AJAX Extensions很重要的一个控件,其强大之处在于不用编写任何客户端脚本,只要在一个页面上添加几个UpdatePanel控件和一个ScriptManager控件就可以自动实现局部更新。通过本文来学习一下UpdatePanel其他的一些使用方法(第二篇)。 ASP.NET AJAX入门系列(6):UpdateProgress控件简单介绍 导读:在ASP.NET AJAX Beta2,UpdateProgress控件已经从“增值”CTP移到了ASP.NET AJAX核心,本文简单介绍一些它的基本用法,翻译自官方文档。 ASP.NET AJAX入门系列(7):使用客户端脚本对UpdateProgress编程 导读:在本篇文章,我们将通过编写JavaScript来使用客户端行为扩展UpdateProgress控件,客户端代码将使用ASP.NET AJAX Library的PageRequestManager,在UpdateProgress控件,将添加一个Button,来允许用户取消异步更新,并且使用客户端脚本来显示或者隐藏进度信息,翻译自官方文档。 ASP.NET AJAX入门系列(8):自定义异常处理 导读:在UpdatePanel控件异步更新时,如果有错误发生,默认情况下会弹出一个Alert对话框显示出错误信息,这对用户来说是不友好的,本文看一下如何在服务端和客户端脚本自定义异常处理,翻译自官方文档。 ASP.NET AJAX入门系列(9):在母版页使用UpdatePanel 导读:本文简单介绍一下在母版页使用UpdatePanel控件,翻译自官方文档。 ASP.NET AJAX入门系列(10):Timer控件简单使用 导读:本文主要通过一个简单示例,让Web页面在一定的时间间隔内局部刷新,来学习一下ASP.NET AJAX的服务端Timer控件的简单使用ASP.NET AJAX入门系列(11):在多个UpdatePanle使用Timer控件 导读:本文将使用Timer控件更新两个UpdatePanel控件,Timer控件将放在UpdatePanel控件的外面,并将它配置为UpdatePanel的触发器,翻译自官方文档 作者:TerryLee 出处:http://terrylee.cnblogs.com
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值