Html连接.NET Ashx

Html代码:

<!DOCTYPE html>
<html>
	<head>
		 <meta charset="utf-8">
		  <meta name="viewport" content="width=device-width, initial-scale=1">
		  <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
		  <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
		  <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>
		  <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
		<title>网格</title>
	</head>
	<script>    
				$(document).ready(function() {
				    $.ajax({
				    url : "http://localhost:14047/witchone.ashx",//请求地址
				    dataType : "json",//数据格式 
				    type : "get",//请求方式
				    async : false,//是否异步请求
				    success : function(data) {   //如何发送成功
				    document.getElementById("ttt1").innerHTML=data["Title"]; 
var json = eval (data["Data"]); for(var i=0;i<json.length;i++){ //遍历data数组 var row=table.insertRow(table.rows.length); var c1=row.insertCell(0); c1.innerHTML=json[i].ID; var c2=row.insertCell(1); c2.innerHTML=json[i].Name; var c3=row.insertCell(2); c3.innerHTML=json[i].Age; } }, }) }) </script> <body> <div > <h2 class="text-center" id='ttt1'></h2> </div> <div> <table id='table' class="table table-bordered"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> </thead> </div> </body> </html>

  .net ashx

public class witchone: IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            Dictionary<string, object> param = new Dictionary<string, object>();
            string ret = "";
            DataTable dt = new DataTable();//创建表
            dt.Columns.Add("ID", typeof(Int32));//添加列
            dt.Columns.Add("Name", typeof(String));
            dt.Columns.Add("Age", typeof(Int32));
            dt.Rows.Add(new object[] { 1, "张三", 20 });//添加行
            dt.Rows.Add(new object[] { 2, "李四", 25 });
            dt.Rows.Add(new object[] { 3, "王五", 30 });
            string data = JsonConvert.SerializeObject(dt, new DataTableConverter());

            param.Add("Title", "Witch One");
            param.Add("RefreshTime", 5);
            param.Add("NowTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            param.Add("Data", data);
            ret = JsonConvert.SerializeObject(param);   
            context.Response.AddHeader("Access-Control-Allow-Origin", "*");
            context.Response.ContentType = "text/html";
            context.Response.Write(ret);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

  

猜你喜欢

转载自www.cnblogs.com/Zingu/p/12195068.html