In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you how ASP.NET uses Ajax to return Json objects, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Create a new html page, such as the registration page "Register.htm"
User registers .msg {color:Red;} user name: password: last name:
Create a new js file, such as reg.js
$(function () {/ / defines the function function clearMsg () {$(".msg") .html ("") that clears the error message. } / / define the function to get the form data. Note that the json object function formData () {return {id: $("# id") .val (), pwd: $("# pwd") .val (), name: $("# xm"). Val ()};} / / the function function reg () {var url = "Register.ashx"; var data = formData () that defines the registration function ClearMsg () $.ajax ({type: 'GET', / / automatically converts the json object to a query string appended to the url, such as: http://localhost:49521/Register.ashx?id=a&pwd=b&name=c url: url, dataType:' json', / / requires the server to return data of type json, such as {"success": true, "message": "registered successfully"} contentType: 'application/json' / / when sending information to the server The type of content encoding data: data, / / data submitted to the server, using data from json objects directly, such as: {"id": "a", "pwd": "b", "name": "c"} (if a string in json format is required You can use JSON.stringify (data) success: function (responseData) {/ / if the response is successful (i.e. 200) if (responseData.success = = true) {/ / responseData is also in json format, such as {"success": true, "message": "registered successfully"} alert (responseData.message) } else {var msgs = responseData.msgs;//msgs object is an array, as follows: / / {"success": false, "message": "Registration failed", "msgs": [{"id": "pwdMsg", "message": "password cannot be empty."}, {"id": "nameMsg", "message": "name cannot be empty."}} for (var I = 0; I < msgs.length) Error +) {$('#'+ msgs.id) .html (msgs.message);}, function () {/ / requires a parameter of type Function, the function to be called when the request fails. This function takes three parameters, namely, the XMLHttpRequest object, the error message, and the captured error object (optional). The ajax event function is as follows: / / function (XMLHttpRequest, textStatus, errorThrown) {/ / normally only one of textStatus and errorThrown contains information / / this; / / the options parameter alert (arguments [1]) passed when this ajax request is called;}}) / / ajax} / / define an initialization function function init () {$("# btnReg") .click (function () {reg ();});} / / call initialization function init ();})
3. Handle ajax requests
Method 1: manually concatenate json strings
Create a new general handler, such as 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 Summary description of namespace WebLogin {/ $codebehindclassname$ / / [WebService (Namespace = "http://tempuri.org/")] [WebServiceBinding (ConformsTo = WsiProfiles.BasicProfile1_1)] public class Register1: IHttpHandler {public void ProcessRequest (HttpContext context) {context.Response.ContentType =" application/json "; / / set the format of the response content to json format string id = context.Request [" id "] String pwd = context.Request ["pwd"]; string name = context.Request ["name"]; List msgList = new List (); if (String.IsNullOrEmpty (id)) {msgList.Add ("{\" id\ ":\" idMsg\ ",\" message\ ":\" user name cannot be empty.\ "}") } if (pwd==null | | pwd== "") {msgList.Add ("{\" id\ ":\" pwdMsg\ ",\" message\ ":\" password cannot be empty.\ "}") / such as: {"id": "pwdMsg", "message": "password cannot be empty."}} if (name==null | | name== "") {msgList.Add ("{\" id\ ":\" nameMsg\ ",\" message\ ":\" name cannot be empty.\ "} string responseText =" If (msgList.Count = = 0) {/ / call background code to write database responseText = "{\" success\ ": true,\" message\ ":\" registered successfully\ "} else {string msgsValue ="; for (int I = 0; I < msgList.Count; iTunes +) {msgsValue + = msgList [I] +", " / / concatenate each string in the list, separated by ",", but there will be more in the end ","} msgsValue=msgsValue.Substring (0, msgsValue.Length-1); / / remove the end "," msgsValue= "[" + msgsValue + "]" / enclosed in "[]", for example: [{"id": "pwdMsg", "message": "password cannot be empty."}, {"id": "nameMsg", "message": "name cannot be empty."}] responseText = "{\" success\ ": false,\" message\ ":\" Registration failed\ ",\" msgs\ ":" + msgsValue + "}" / most like: {"success": false, "message": "Registration failed", "msgs": [{"id": "pwdMsg", "message": "password cannot be empty."}, {"id": "nameMsg", "message": "name cannot be empty."]} context.Response.Write (responseText);} public bool IsReusable {get {return false }
Method 2: use the Json.NET tool to convert C# objects into json output
1. Create a new information class "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. Create a new class "ResponseData.cs" that returns json objects.
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 msgs; public List 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 msgs) {this.success = success; this.message = message; this.msgs = msgs;}
3. Go to the official website to download Json.NET and copy the reference
Official website: http://www.newtonsoft.com/json
Download address: http://pan.baidu.com/s/1nvz9JBV
After downloading and unzipping, copy "Newtonsoft.Json.dll" to the project's "bin" directory and reference it (note that it is consistent with the. Net version)
4. Create a new general processor "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 / / introduce the summary description of namespace WebLogin {/ $codebehindclassname$ / / [WebService (Namespace = "http://tempuri.org/")] [WebServiceBinding (ConformsTo = WsiProfiles.BasicProfile1_1)] public class reg: IHttpHandler {public void ProcessRequest (HttpContext context) {context.Response.ContentType =" application/json "; / / set the format of the response content to json format string id = context.Request [" id "] String pwd = context.Request ["pwd"]; string name = context.Request ["name"]; List msgs = new List (); if (String.IsNullOrEmpty (id)) {msgs.Add (new Msg ("idMsg", "user name cannot be empty.")) } if (String.IsNullOrEmpty (pwd)) {msgs.Add (new Msg ("pwdMsg", "password cannot be empty.");} if (String.IsNullOrEmpty (name)) {msgs.Add (new Msg ("nameMsg", "name cannot be empty.");} ResponseData rData If (msgs.Count = = 0) {/ / call the registration method and write to the database rData = new ResponseData (true, "registration succeeded.");} else {rData = new ResponseData (false, "registration failed.", msgs);} context.Response.Write (JsonConvert.SerializeObject (rData)) / / directly call the method to convert rData to json string} public bool IsReusable {get {return false;}
4. the completion effect is as shown in the picture.
These are all the contents of the article "how ASP.NET returns Json objects with Ajax". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.