This article mainly introduces the method that ASP. NET uses Ajax to return JSON object, very good, have reference value, need friend can refer to next
First, create a new HTML page, such as the registration page "Register.htm"
<! DOCTYPE html>
second, create a new JS file, such as: Reg.js
$ (function () {//) defines the functions Clearmsg () {$ (". Msg") that clears the error message. HTML (""); }//define the function to get the form data, note the return JSON object function FormData () {return {ID: $ ("#id"). Val (), PWD: $ ("#pwd"). Val (), NA Me: $ ("#xm"). Val ()}; }//define function of registration function Reg () {var url = "Register.ashx"; var data = FormData (); 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 a JSON type of data, such as: {"Success": TRUE, "message": "Registered Successfully"} ContentType: ' Applicatio N/json ',///Send information to the server, the type of content encoding data:data,//data submitted to the server, directly using the JSON object data, such as: {"id": "A", "pwd": "B", "Name": "C"} (If a JSON-formatted string is required, use json.stringify (data)) Success:function (responsedata) {//If the response succeeds (that is, a.) if (responsedata.succe SS = = true) {//responsedata is also in JSON format, such as: {"Success": TRUE, "message": "Registered Successfully"} alert (Responsedata.message); The 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; i++) {$ (' # ' + msgs[i].id). HTML (msgs[i].message); }}, Error:function () {//requires a parameter of type function, the function called when the request fails. The function has 3 parameters, the XMLHttpRequest object, the error message, and optionally the error object being captured. The Ajax event functions are as follows://function (XMLHttpRequest, Textstatus, Errorthrown) {//normally textstatus and Errorthrown only one of them contains information// This The Options parameter alert (Arguments[1]) that was passed when calling this Ajax request; }});//ajax}//defines an initializer function, init () {$ ("#btnReg"). Click (function () {reg (); }); }//Call initialization function init ();});
Third, processing AJAX requests
Method One: Manually stitching the JSON string
Create a new generic 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;namespace WebLogin{// <summary>///$codebehindclassname $ summary description///</summary> [WebService (Namespace = "http://tempuri.org/")] [ WebServiceBinding (ConformsTo = wsiprofiles.basicprofile1_1)] public class Register1:ihttphandler {public void Proc Essrequest (HttpContext context) {context. Response.ContentType = "Application/json";//The format of the response content is the JSON format 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\ ": \" User name cannot be empty. \ "}"); } if (Pwd==null | | pwd== "") {Msglist.add ("{\" id\ ": \" pwdmsg\ ", \" message\ ": \" password cannot be empty. \ "}");//shape: {"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 back code to write to database responsetext = "{\" success\ ": True,\" message\ ": \" registration succeeded \ "}"; } else {string msgsvalue = ""; for (int i = 0; i < Msglist.count; i++) {msgsvalue + = Msglist[i] + ",";//Connect each string in the list, separated by "," but eventually More ","} msgsvalue=msgsvalue.substring (0, msgsvalue.length-1);//Remove End of "," Msgsvalue = "[" + Msgsvalue + "]";//with "[]", such as: [{"id": "pwdmsg", "message": "Password cannot be empty."},{"id": "namemsg", "message": "Name cannot be empty."} ResponseText = "{\" success\ ": False,\" message\ ": \" registration failed \ ", \" Msgs\ ":" + Msgsvalue + "}"; The most metaphysical: {"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 Two: Use the Json.NET tool to convert C # objects to JSON output
1, 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 a JSON object
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;} The 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, to the official website download json.net, and copy the reference
Official website: Http://www.newtonsoft.com/json
Download Address: Http://pan.baidu.com/s/1nvz9JBV
Copy the "Newtonsoft.Json.dll" to the project's "bin" Directory and reference (note the consistency with the. NET version) after downloading the extract.
4, the new general processing program "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 namespace weblogin{//<summary>///$codebehindclassname $ for a summary description///</summary> [WebService (Namespac E = "http://tempuri.org/")] [webservicebinding (ConformsTo = wsiprofiles.basicprofile1_1)] public class Reg:ihttphandle R {public void ProcessRequest (HttpContext context) {context. Response.ContentType = "Application/json";//The format of the response content is the JSON format 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", "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, write to Database RData = new ResponseData (True, "registration succeeded."); } else {rData = new ResponseData (False, "registration failed.", msgs); } context. Response.Write (Jsonconvert.serializeobject (RData));//Direct Call method converts rData to JSON string} public bool IsReusable {get {return false; } } }}
Iv. completion of the effect
"Recommended"
1. ASP. NET free Video Tutorials
2. Detailed JS operation XML object converted to JSON object
3. The sample code for JavaScript traversing the key and any JS object properties of the JSON object (figure)