ASP.NET使用Ajax返回Json對(duì)象的方法
一、新建一個(gè)html頁面,如注冊(cè)頁面"Register.htm"
<!DOCTYPE html> <html > <head> <title>用戶注冊(cè)</title> <meta charset="utf-8" /> <style type="text/css"> .msg { color:Red; } </style> </head> <body> <!-- 因?yàn)槭莂jax提交,html表單控件可以不必放在form里,且不能使用提交按紐(type="submit"),而使用普通按紐(type="button") --> 用戶名:<input type="text" name="id" id="id" /><span id="idMsg" class="msg"></span><br /> <!-- span用來顯示錯(cuò)誤信息 --> 密 碼:<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="注冊(cè)" /> <script type="text/javascript" src="bootstrap/js/jquery.js"> </script> <script src="reg.js" type="text/javascript"></script> </body> </html>
二、新建一js文件,如:reg.js
$(function() { //定義清除錯(cuò)誤信息的函數(shù) function clearMsg() { $(".msg").html(""); } //定義獲取表單數(shù)據(jù)的函數(shù),注意返回json對(duì)象 function formData() { return { id: $("#id").val(), pwd: $("#pwd").val(), name: $("#xm").val() }; } //定義注冊(cè)功能的函數(shù) function reg() { var url = "Register.ashx"; var data = formData(); clearMsg(); $.ajax({ type: 'GET', //自動(dòng)會(huì)把json對(duì)象轉(zhuǎn)換為查詢字符串附在url后面如:http://localhost:49521/Register.ashx?id=a&pwd=b&name=c url: url, dataType: 'json', //要求服務(wù)器返回一個(gè)json類型的數(shù)據(jù),如:{"success":true,"message":"注冊(cè)成功"} contentType: 'application/json',//發(fā)送信息給服務(wù)器時(shí),內(nèi)容編碼的類型 data: data, //提交給服務(wù)器的數(shù)據(jù),直接使用json對(duì)象的數(shù)據(jù),如:{"id":"a","pwd":"b","name":"c"}?。ㄈ绻骿son格式的字符串,可使用用JSON.stringify(data)) success: function(responseData) {//如果響應(yīng)成功(即200) if (responseData.success == true) {//responseData也是json格式,如:{"success":true,"message":"注冊(cè)成功"} alert(responseData.message); } else { var msgs = responseData.msgs;//msgs對(duì)象是一個(gè)數(shù)組,如下所示: //{"success":false,"message":"注冊(cè)失敗","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類型的參數(shù),請(qǐng)求失敗時(shí)被調(diào)用的函數(shù)。該函數(shù)有3個(gè)參數(shù),即XMLHttpRequest對(duì)象、錯(cuò)誤信息、捕獲的錯(cuò)誤對(duì)象(可選)。ajax事件函數(shù)如下: //function(XMLHttpRequest, textStatus, errorThrown){ //通常情況下textStatus和errorThrown只有其中一個(gè)包含信息 //this; //調(diào)用本次ajax請(qǐng)求時(shí)傳遞的options參數(shù) alert(arguments[1]); } });//ajax } //定義一個(gè)初始化函數(shù) function init() { $("#btnReg").click(function() { reg(); }); } //調(diào)用初始化函數(shù) init(); });
三、處理ajax請(qǐng)求
方法一:手動(dòng)拼接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";//設(shè)置響應(yīng)內(nèi)容的格式是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) { //調(diào)用后臺(tái)代碼寫入數(shù)據(jù)庫(kù) responseText = "{\"success\":true,\"message\":\"注冊(cè)成功\"}"; } else { string msgsValue = ""; for (int i = 0; i < msgList.Count; i++) { msgsValue += msgList[i] + ",";//將列表中的每一個(gè)字符串連接起來,用","隔開,不過最后還會(huì)多"," } msgsValue=msgsValue.Substring(0, msgsValue.Length - 1);//去掉末尾的"," msgsValue = "[" + msgsValue + "]";//用"[]"括起來,如:[{"id":"pwdMsg","message":"密碼不能為空."},{"id":"nameMsg","message":"姓名不能為空."}] responseText = "{\"success\":false,\"message\":\"注冊(cè)失敗\",\"msgs\":" + msgsValue + "}"; //最的形如:{"success":false,"message":"注冊(cè)失敗","msgs":[{"id":"pwdMsg","message":"密碼不能為空."},{"id":"nameMsg","message":"姓名不能為空."}]} } context.Response.Write(responseText); } public bool IsReusable { get { return false; } } } }
方法二:使用Json.NET工具來將C#對(duì)象轉(zhuǎn)換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對(duì)象的類“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、去官網(wǎng)下載Json.NET,并復(fù)制引用
官網(wǎng):http://www.newtonsoft.com/json
下載地址:http://pan.baidu.com/s/1nvz9JBV
下載解壓后將“Newtonsoft.Json.dll”復(fù)制到項(xiàng)目的“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";//設(shè)置響應(yīng)內(nèi)容的格式是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) { //調(diào)用注冊(cè)方法,寫入數(shù)據(jù)庫(kù) rData = new ResponseData(true, "注冊(cè)成功."); } else { rData = new ResponseData(false, "注冊(cè)失敗.", msgs); } context.Response.Write(JsonConvert.SerializeObject(rData));//直接調(diào)用方法將rData轉(zhuǎn)換為json字符串 } public bool IsReusable { get { return false; } } } }
四、完成效果如圖
以上所述是小編給大家介紹的ASP.NET使用Ajax返回Json對(duì)象的方法,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
- Vue.js與 ASP.NET Core 服務(wù)端渲染功能整合
- Asp.NetCore1.1版本去掉project.json后如何打包生成跨平臺(tái)包
- ASP.NET MVC中jQuery與angularjs混合應(yīng)用傳參并綁定數(shù)據(jù)
- ASP.NET Core Project.json文件(5)
- ASP.NET core Web中使用appsettings.json配置文件的方法
- C#后臺(tái)調(diào)用前臺(tái)JS函數(shù)方法
- mongodb使用c#驅(qū)動(dòng)數(shù)據(jù)插入demo
- c#操作mongodb插入數(shù)據(jù)效率
- C#引用類型和值類型的適用場(chǎng)合和區(qū)別
- asp.net使用JS+form表單Post和Get方式提交數(shù)據(jù)
相關(guān)文章
ASP.NET MVC使用EasyUI的datagrid多選提交保存教程
ASP.NET MVC使用EasyUI的datagrid多選提交保存教程,需要的朋友可以參考下。2011-12-12.NET全局靜態(tài)可訪問IServiceProvider的過程詳解(支持Blazor)
為解決在靜態(tài)方法中訪問依賴注入(DI)容器的問題,提出了通過DependencyInjection.StaticAccessor包實(shí)現(xiàn)靜態(tài)訪問,這一方法特別適用于需要在靜態(tài)方法中獲取范圍內(nèi)(Scoped)服務(wù)的場(chǎng)景,感興趣的朋友跟隨小編一起看看吧2024-09-09URL中去除指定參數(shù)實(shí)現(xiàn)C#代碼
URL中去除指定參數(shù)在項(xiàng)目開發(fā)中還是很常見的,本文將介紹下它在c#代碼中的實(shí)現(xiàn),感興趣的朋友可以參考下哈2013-04-04asp.net實(shí)現(xiàn)在XmlTextWriter中寫入一個(gè)CDATA的方法
這篇文章主要介紹了asp.net實(shí)現(xiàn)在XmlTextWriter中寫入一個(gè)CDATA的方法,結(jié)合實(shí)例形式分析了XmlTextWriter寫入CDATA的步驟與相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-04-04ASP.NET記住登陸用戶名的具體實(shí)現(xiàn)
ASP.NET記住登陸用戶名的具體實(shí)現(xiàn),需要的朋友可以參考一下2013-06-06Asp.Net 無刷新文件上傳并顯示進(jìn)度條的實(shí)現(xiàn)方法及思路
這篇文章詳細(xì)介紹了無刷新文件上傳并顯示進(jìn)度條的思路和代碼,有需要的朋友可以參考一下2013-06-06Asp.net的GridView控件實(shí)現(xiàn)單元格可編輯方便用戶使用
考慮到用戶使用方便,減少?gòu)棾鲰撁妫捎命c(diǎn)“編輯”按鈕無需彈出頁面直接當(dāng)前行的單元格內(nèi)容就能編輯,思路及代碼如下,有此需求的朋友可以參考下,希望對(duì)大家有所幫助2013-08-08