jquery使用ajax读取后台数据在表格中显示

快乐打工仔 分类:实例代码

本章节介绍一下如何从数据库读取数据,然后通过ajax显示于前台表格中。

使用原生的方式可以参阅前台怎样获取后台ajax数据简单介绍一章节。

下面介绍一下如何使用jquery的ajax实现此功能。

代码实例如下:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>犀牛前端部落</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
  $("#bt").click(function () {
    var str = "<table>";
    $.ajax({
      url: "demo/ajax/net/jqueryAjax.ashx",
      data: {},
      type: "get",
      async: true,
      dataType:"json",
      success: function (json) {
        $.each(json, function (index, obj) {
          $.each(obj, function (y, data) {
            str = str + "<tr>";
            str = str + "<td>" + data["username"] 
            + "</td><td>" + data["address"] 
            + "</td><td>" + data["score"] + "</td>";
            str = str + "</tr>";
          })
        })
        str = str + "</tr></table>";
        $("#antzone").html(str);
      }
    });
  })
})
</script>
</head>
<body>
<div id="antzone"></div>
<input type="button" id="bt" value="查看效果"/>
</body>
</html>

上面的代码实现了我们的要求,通过jquery的ajax方式实现了获取后台数据的功能。

c#代码如下:

namespace ajax
{
    /// <summary>
    /// jqueryAjax 的摘要说明
    /// </summary>
    public class jqueryAjax : IHttpHandler
    {
 
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            DataSet ds = done();
            string jsonStr = GetJsonByDataset(ds);
            context.Response.Write(jsonStr);
        }
        private DataSet done()
        {
            string connString = ConfigurationManager.ConnectionStrings["access_con"].ConnectionString;
            string configPath = ConfigurationManager.ConnectionStrings["access_path"].ConnectionString;
            string conPath = HttpContext.Current.Server.MapPath(configPath);
            OleDbConnection conn = new OleDbConnection(connString + conPath);
 
            string sql = "select * from code";
            OleDbCommand cmd = new OleDbCommand(sql, conn);
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "ds");
            return ds;
        }
 
        private string GetJsonByDataset(DataSet ds)
        {
            if (ds == null || ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0)
            {
                //如果查询到的数据为空则返回标记ok:false
                return "{\"ok\":false}";
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            foreach (DataTable dt in ds.Tables)
            {
                sb.Append(string.Format("\"{0}\":[", dt.TableName));
 
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("{");
                    for (int i = 0; i < dr.Table.Columns.Count; i++)
                    {
                        sb.AppendFormat("\"{0}\":\"{1}\",", dr.Table.Columns[i].ColumnName.Replace("\"", "\\"").Replace("\'", "\\'"), ObjToStr(dr[i]).Replace("\"", "\\"").Replace("\'", "\\'")).Replace(Convert.ToString((char)13), "\r\n").Replace(Convert.ToString((char)10), "\r\n");
                    }
                    sb.Remove(sb.ToString().LastIndexOf(','), 1);
                    sb.Append("},");
                }
 
                sb.Remove(sb.ToString().LastIndexOf(','), 1);
                sb.Append("],");
            }
            sb.Remove(sb.ToString().LastIndexOf(','), 1);
            sb.Append("}");
            return sb.ToString();
        }
        private string ObjToStr(object ob)
        {
            if (ob == null)
            {
                return string.Empty;
            }
            else
                return ob.ToString();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

回复

我来回复
  • 暂无回复内容