這篇文章主要介紹了ASP.NET使用Ajax返回Json對象的方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
一、建立一個html頁面,如註冊頁面"Register.htm"
<!DOCTYPE html><html ><head> <title>使用者註冊</title> <meta charset="utf-8" /> <style type="text/css"> .msg { color:Red; } </style></head><body> <!-- 因為是ajax提交,html表單控制項可以不必放在form裡,且不能使用提交按紐(type="submit"),而使用普通按紐(type="button") --> 使用者名稱:<input type="text" name="id" id="id" /><span id="idMsg" class="msg"></span><br /> <!-- span用來顯示錯誤資訊 --> 密 碼:<input type="password" name="pwd" id="pwd" /><span id="pwdMsg" class="msg"></span><br /> 姓 名:<input type="text" name="name" id="xm" /><span id="nameMsg" class="msg"></span><br /> <input id="btnReg" type="button" value="註冊" /> <script type="text/javascript" src="bootstrap/js/jquery.js"> </script> <script src="reg.js" type="text/javascript"></script> </body></html>
二、建立一js檔案,如:reg.js
$(function() { //定義清除錯誤資訊的函數 function clearMsg() { $(".msg").html(""); } //定義擷取表單資料的函數,注意返回json對象 function formData() { return { id: $("#id").val(), pwd: $("#pwd").val(), name: $("#xm").val() }; } //定義註冊功能的函數 function reg() { var url = "Register.ashx"; var data = formData(); clearMsg(); $.ajax({ type: 'GET', //自動會把json對象轉換為查詢字串附在url後面如:http://localhost:49521/Register.ashx?id=a&pwd=b&name=c url: url, dataType: 'json', //要求伺服器返回一個json類型的資料,如:{"success":true,"message":"註冊成功"} contentType: 'application/json',//發送資訊給伺服器時,內容編碼的類型 data: data, //提交給伺服器的資料,直接使用json對象的資料,如:{"id":"a","pwd":"b","name":"c"} (如果要求json格式的字串,可使用用JSON.stringify(data)) success: function(responseData) {//如果響應成功(即200) if (responseData.success == true) {//responseData也是json格式,如:{"success":true,"message":"註冊成功"} alert(responseData.message); } else { var msgs = responseData.msgs;//msgs對象是一個數組,如下所示: //{"success":false,"message":"註冊失敗","msgs":[{"id":"pwdMsg","message":"密碼不可為空."},{"id":"nameMsg","message":"姓名不可為空."}]} for (var i = 0; i < msgs.length; i++) { $('#' + msgs[i].id).html(msgs[i].message); } } }, error: function() { //要求為Function類型的參數,請求失敗時被調用的函數。該函數有3個參數,即XMLHttpRequest對象、錯誤資訊、捕獲的錯誤對象(可選)。ajax事件函數如下: //function(XMLHttpRequest, textStatus, errorThrown){ //通常情況下textStatus和errorThrown只有其中一個包含資訊 //this; //調用本次ajax請求時傳遞的options參數 alert(arguments[1]); } });//ajax } //定義一個初始化函數 function init() { $("#btnReg").click(function() { reg(); }); } //調用初始化函數 init();});
三、處理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”
using System;using System.Data;using System.Configuration;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;namespace WebLogin{ public class Msg { private string id; public string Id { get { return id; } set { id = value; } } private string message; public string Message { get { return message; } set { message = value; } } public Msg(string id, string message) { this.id = id; this.message = message; } }}
2、建立返回json對象的類“ResponseData.cs”
using System;using System.Data;using System.Configuration;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using System.Collections.Generic;namespace WebLogin{ public class ResponseData { private bool success; public bool Success { get { return success; } set { success = value; } } private string message; public string Message { get { return message; } set { message = value; } } private List<Msg> msgs; public List<Msg> Msgs { get { return msgs; } set { msgs = value; } } public ResponseData(bool success, string message) { this.success = success; this.message = message; } public ResponseData(bool success, string message, List<Msg> msgs) { this.success = success; this.message = message; this.msgs = msgs; } }}
3、去官網下載Json.NET,並複製引用
下載解壓後將“Newtonsoft.Json.dll”複製到項目的“bin”目錄中,並引用(注意和.net版本保持一致)
4、建立一般處理常式“reg.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;using Newtonsoft.Json;//引入namespace WebLogin{ /// <summary> /// $codebehindclassname$ 的摘要說明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class reg : 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<Msg> msgs = new List<Msg>(); if (String.IsNullOrEmpty(id)) { msgs.Add(new Msg("idMsg", "使用者名稱不可為空.")); } if (String.IsNullOrEmpty(pwd)) { msgs.Add(new Msg("pwdMsg", "密碼不可為空.")); } if (String.IsNullOrEmpty(name)) { msgs.Add(new Msg("nameMsg", "姓名不可為空.")); } ResponseData rData; if (msgs.Count == 0) { //調用註冊方法,寫入資料庫 rData = new ResponseData(true, "註冊成功."); } else { rData = new ResponseData(false, "註冊失敗.", msgs); } context.Response.Write(JsonConvert.SerializeObject(rData));//直接調用方法將rData轉換為json字串 } public bool IsReusable { get { return false; } } }}
四、完成效果