1.页面ajax传值到一般处理程序
function btnOnClick() { alert(1); $.ajax({ url: "../ashx/HanderTest.ashx", type: "GET", dataType: "json", success: function (data) { alert("成功"); alert(data.status); var obj = data.rows; var html = ""; html += "<ul>"; for (var i = 0; i < obj.length; i++) { html += "<li>" + obj[i].Product + "</li>"; html += "<li>" + obj[i].Description + "</li>"; } html += "</ul>"; $("#span_tr").append(html); //document.getElementById("span_tr").append = html; }, fail: function () { alert("失败"); }, error: function () { alert("错误"); } }); }
2.一般处理程序转换json
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; #region DataTable类型数据 DataTable dt = new DataTable("Datas"); DataColumn dc = null; dc = dt.Columns.Add("ID", Type.GetType("System.Int32")); dc.AutoIncrement = true;//自动增加 dc.AutoIncrementSeed = 1;//起始为1 dc.AutoIncrementStep = 1;//步长为1 dc.AllowDBNull = false; dc = dt.Columns.Add("Product", Type.GetType("System.String")); dc = dt.Columns.Add("Description", Type.GetType("System.String")); for (int i = 0; i < 5; i++) { DataRow dr = dt.NewRow(); ; dr["Product"] = "测试产品" + i; dr["Description"] = "测试产品描述" + i; dt.Rows.Add(dr); } #endregion #region JSON 格式化 StringBuilder Str = new StringBuilder(); Str.Append("{\"status\":200,"); Str.Append("\"rows\":["); DataRowCollection drc = dt.Rows; for (int i = 0; i < drc.Count; i++) { Str.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { string strKey = dt.Columns[j].ColumnName;//列名 string strValue = drc[i][j].ToString();//列名对应的值 if (j < dt.Columns.Count - 1) { Str.AppendFormat("\"{0}\":\"{1}\",", strKey, strValue);//有逗号 } else { Str.AppendFormat("\"{0}\":\"{1}\"", strKey, strValue);//无逗号 } } Str.Append("},"); } Str.Remove(Str.Length - 1, 1);//移除最后一个逗号 Str.Append("]}"); #endregion string jsonstr = Str.ToString(); context.Response.Write(jsonstr); }
时间: 2024-11-05 18:55:39