前台代码:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxJson.aspx.cs" Inherits="XML操作.AjaxJson" %> 2 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <title></title> 8 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 9 <script src="jquery-3.2-vsdoc2.js" type="text/javascript"></script> 10 <script type="text/javascript" language="javascript"> 11 jQuery(function () { 12 jQuery("#button1").click(function () { 13 var text1 = jQuery("#text1").val(); 14 var text2 = jQuery("#text2").val(); 15 16 jQuery.ajax({ 17 type: "post", 18 url: "Json.ashx", 19 data: "t1=" + escape(text1) + "&t2=" + escape(text2) + "", 20 //dataType: "json", 21 error: function (err) { 22 window.alert(err.status); 23 }, 24 success: function (result) { 25 var object = eval("(" + result + ")"); 26 //window.alert(object); 27 jQuery("#text1+em").eq(0).html("您输入的是:" + object.name); 28 jQuery("#text2+em").eq(0).html("您输入的是:" + object.sex); 29 } 30 31 }); 32 33 }) 34 35 36 }) 37 </script> 38 </head> 39 <body> 40 <form id="form1" runat="server"> 41 <div> 42 <input type="text" id="text1" /><em></em><input type="text" id="text2"/><em></em> 43 <input type="button" id="button1" value="执行" /> 44 </div> 45 </form> 46 </body> 47 </html>
Json代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 6 namespace XML操作 7 { 8 /// <summary> 9 /// Json 的摘要说明 10 /// </summary> 11 public class Json : IHttpHandler 12 { 13 14 public void ProcessRequest(HttpContext context) 15 { 16 string t1= context.Request.Params["t1"].ToString(); 17 string t2 = context.Request.Params["t2"].ToString(); 18 string st = "{"name":" + t1 + ","sex":" + t2 + "}"; 19 context.Response.Write(st); 20 21 } 22 23 public bool IsReusable 24 { 25 get 26 { 27 return false; 28 } 29 } 30 31 32 static string GetMd5Upper32(string input) 33 { 34 return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(input, "MD5"); 35 } 36 37 //[System.Web.Services.WebMethod] 38 public static string GetMd5(string input, int format) 39 { 40 switch (format) 41 { 42 case 1: 43 return GetMd5Upper32(input); 44 case 2: 45 return GetMd5Upper32(input).ToLower(); 46 case 3: 47 return GetMd5Upper32(input).Substring(8, 16); 48 case 4: 49 return GetMd5Upper32(input).Substring(8, 16).ToLower(); 50 default: 51 return GetMd5Upper32(input); 52 } 53 } 54 } 55 }