<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>getJson+ashx实现数据交互(入门级)</title> <%--引用jQuery框架,有时jQuery框架不对,会出现无法getJson无法调用ashx页面--%> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> $(document).ready(function() { $.getJSON( "Handler/nameData.ashx",{type: "1"},function(json) { $.each(json,function(i) { $("#cat-list").append("<li>id:" + json[i].id + " title:" + json[i].title + "</li>") //json为从ashx页面回传的值 }) }); }); </script> </head> <body> <form id="form1" runat="server"> <div id="categories"> <ul id="cat-list"></ul> </div> </form> </body> </html>
ashx页面
<%@ WebHandler Language="C#" Class="nameData" %> using System; using System.Web; using System.Data; using System.Text; using System.Data.Common; using mshopClass; public class nameData : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain";
//调试 //string data = "[{id:1,title:\"33F2845A-78C1-4F23-9185-06A7ABA69540\"},{id:2,title:\"3921750C-428F-451F-B90F-1EBF6B2B1B8C\"},{id:3,title:\"BC8133D0-85F3-@R_403_448@3-B457-449087523824\"},{id:4,title:\"E0332DA0-E8B4-44E6-8053-90AF681ED7B9\"},{id:5,title:\"C8D9A1D5-8052-446B-A889-27ED7F903D96\"}]"; //调试 StringBuilder tb = new StringBuilder(); string sql3 = "select top 30 id,title,cdate from test"; DataTable dt3 = mallCtr.sqlTable(sql3); tb.Append(DataTableToJSON(dt3)); //将DataTabel转换成json格式 context.Response.Write(tb.ToString()); //将数据回传到test.aspx页面,json格式不正确,数据不能正常返回给前台页面 } public bool IsReusable { get { return false; } } /// <summary> /// 将dt转化成Json数据 格式如 table[{id:1,title:'体育'},id:2,title:'娱乐'}] /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string DataTableToJSON(DataTable dt) { StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.Append("["); for (int i = 0; i < dt.Rows.Count; i++) { if (i > 0) jsonBuilder.Append(","); jsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { if (j > 0) jsonBuilder.Append(","); jsonBuilder.Append(dt.Columns[j].ColumnName.ToLower() + ": '" + dt.Rows[i][j].ToString().Replace("\t"," ").Replace("\r"," ").Replace("\n"," ").Replace("\'","\\\'") + "'"); } jsonBuilder.Append("}"); } jsonBuilder.Append("]"); return jsonBuilder.ToString(); } }
实例下载地址:getJson+ashx实现数据交互实例下载
原文链接:https://www.f2er.com/json/290211.html