码迷,mamicode.com
首页 > 其他好文 > 详细

为前端提供数据

时间:2014-12-13 23:19:53      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   http   io   ar   color   os   使用   

        随着HTML5和CSS3在应用程序开发中地大量使用,市场中在IOS工程师和Android工程师之外多了一种需求——Web前端工程师。在这个用户至上的市场下,客户越来越重视呈现在他们眼前的形式,包括熟悉的网页等。也许你是做算法设计的,也许你是做数据模型设计的,也许你是做系统架构设计的……但是,我相信你看完下面的几个网站,也会开始对呈现方式有所看法。

       1. 班得瑞 http://www.bandari.net/

       2. 临沧银毫茶业 http://www.lcyhcy.com/

       3. Ghost博客中文版 http://ghost.diancloud.com

       尽管这些网页设计得如此优雅,但是还需要有数据的支撑。不管是新闻还是产品展示,都离不开数据库为页面提供需要的数据。因此,这里提供一种简单方式使得前端的页面拿到需要的数据,让前端工程师把主要的精力放在界面设计上,快速完成项目的开发。另外,让前端工程师和数据开发工程师都各尽其职,保证项目的并行推进。

       废话一堆,下面进入正题。这里的提供的方式是:服务端以一般处理程序(.ashx)的方式提供数据接口,客户端通过jQuery中ajax的jsonp方式读取数据并呈现。开始吧……

      第一步:编写服务端的数据接口

      1. 一般处理程序(DataServicesHandler.ashx)

 1 <%@ WebHandler Language="C#" Class="DataServicesHandler" %>
 2 
 3 using System;
 4 using System.Web;
 5 using System.Data;
 6 using System.Collections.Generic;
 7 
 8 public class DataServicesHandler : IHttpHandler {
 9     
10     public void ProcessRequest (HttpContext context) {
11         context.Response.ContentType = "text/plain";
12         Dictionary<string, string> customParams = new Dictionary<string, string>();
13         // 取到callback函数名
14         customParams["Callback"] = context.Request["callback"];
15         
16         // 数据服务提供的Json数据
17         DataTable allBulletins = DbHelper.GetWholeBulletins();
18         customParams["JsonData"] = ToJson.DatatableToJson(allBulletins, "Bulletin");
19         
20         // 数据传回客户端的形式:callback+(json)
21         customParams["JsonpClient"] = string.Format("{0}({1})", customParams["Callback"], customParams["JsonData"]);
22         context.Response.Write(customParams["JsonpClient"]);
23         context.Response.End();
24     }
25  
26     public bool IsReusable {
27         get {
28             return false;
29         }
30     }
31 
32 }

      2. 数据库辅助类(DbHelper.cs)

bubuko.com,布布扣
 1 using System;
 2 using System.Data;
 3 using System.Data.SqlClient;
 4 using System.Configuration;
 5 
 6 /// <summary>
 7 /// 与DBMS交互
 8 /// </summary>
 9 public sealed class DbHelper
10 {
11     public static DataTable GetWholeBulletins()
12     {
13         DataTable resultDataTable = new DataTable();
14 
15         string connString = ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString;
16         string query = "SELECT BulletinID,BulletinTitle,BulletinContent,BulletinTime FROM Bulletin";
17         using (SqlDataAdapter sqlAdapter = new SqlDataAdapter(query, connString))
18         {
19             sqlAdapter.Fill(resultDataTable);
20             sqlAdapter.Dispose();
21         }
22 
23         return resultDataTable;
24     }
25 }
View Code

      3. JSON辅助类(ToJson.cs)

bubuko.com,布布扣
 1 using System;
 2 using System.Text;
 3 using System.Data;
 4 
 5 /// <summary>
 6 /// DataTable转成Json
 7 /// </summary>
 8 public sealed class ToJson
 9 {
10     /// <summary>
11     /// Convert datatable to json.
12     /// </summary>
13     public static string DatatableToJson(DataTable dt)
14     {
15         StringBuilder jsonBuilder = new StringBuilder();
16         jsonBuilder.Append("[");
17         for (int i = 0; i < dt.Rows.Count; i++)
18         {
19             jsonBuilder.Append("{");
20             for (int j = 0; j < dt.Columns.Count; j++)
21             {
22                 jsonBuilder.Append("\"");
23                 jsonBuilder.Append(dt.Columns[j].ColumnName);
24                 jsonBuilder.Append("\":\"");
25                 jsonBuilder.Append(dt.Rows[i][j].ToString());
26                 jsonBuilder.Append("\",");
27             }
28             jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
29             jsonBuilder.Append("},");
30         }
31         jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
32         jsonBuilder.Append("]");
33         return jsonBuilder.ToString();
34     }
35     /// <summary>
36     /// Convert datatable to json with tablename.
37     /// </summary>
38     public static string DatatableToJson(DataTable dt, string tn)
39     {
40         StringBuilder jsonBuilder = new StringBuilder();
41         jsonBuilder.Append("{\"" + tn + "\":");
42         jsonBuilder.Append(DatatableToJson(dt));
43         jsonBuilder.Append("}");
44         return jsonBuilder.ToString();
45     }
46 }
View Code

      第二步:编写客户端的页面

 1 <!doctype html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8" />
 5     <meta name="viewport" content="width=device-width,initial-scale=1.0" />
 6     <title>UI</title>
 7     <link href="css/bootstrap.min.css" rel="stylesheet" />
 8     <!--[if lt IE 9]>
 9         <script src="js/html5.js"></script>
10     <![endif]-->
11 </head>
12 <body>
13     <div class="container">
14         <h2 class="page-header">数据服务<small>&nbsp;ASHX&WebService</small></h2>
15         <table class="table table-bordered table-striped">
16             <thead>
17                 <tr>
18                     <th>公告编号</th>
19                     <th>公告标题</th>
20                     <th>发布时间</th>
21                 </tr>
22             </thead>
23             <tbody id="bulletin"></tbody>
24         </table>
25     </div>
26     <!--脚本Scripts-->
27     <script src="js/jquery.min.js"></script>
28     <script src="js/bootstrap.min.js"></script>
29     <script src="js/modules/index.js"></script>
30 </body>
31 </html>

      第三步:编写客户端与服务端连接的脚本

 1 var handlerHttp = "http://127.0.0.1:9001/DataServicesHandler.ashx?";
 2 
 3 $(document).ready(function () {
 4     Init();
 5 });
 6 
 7 // 数据服务ashx
 8 function Init () {
 9     var ajaxOptions = {
10         url: handlerHttp + "callback=?",
11         dataType: "jsonp",
12         success: function (data) {
13             var htmlString = "";
14             if (data) {
15                 $.each(data.Bulletin, function (index, value) {
16                     htmlString += "<tr title=‘" + value.BulletinContent + "‘>";
17                     htmlString += "<td>" + value.BulletinID + "</td>";
18                     htmlString += "<td>" + value.BulletinTitle + "</td>";
19                     htmlString += "<td>" + value.BulletinTime + "</td>";
20                     htmlString += "</tr>";
21                 });
22             }
23             $("#bulletin").html(htmlString);
24         },
25         error: function () {
26             alert("DataServicesHandler.ashx")
27         }
28     };
29     $.ajax(ajaxOptions);
30 }

      通过以上简单的三大步,就能为优雅的网页提供数据支撑,从而使得用户在享受的体验下获取需要的信息,何乐而不为!

参考链接:http://www.cnblogs.com/lei2007/archive/2013/01/30/2882942.html

代码下载:DataServices.rar

为前端提供数据

标签:android   style   blog   http   io   ar   color   os   使用   

原文地址:http://www.cnblogs.com/jordenbruce/p/dataservice.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!