实现根据用户名查询用户信息,要求用AJAX
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <meta charset="utf-8" /> <style> table{ width:500px; border: 1px solid #ccc; border-collapse:collapse; } table td{ border: 1px solid #ccc; padding:5px; } #nav{ width:450px; text-align:center; } </style> <script src="js/jquery-3.3.1.js"></script> <script> $(function () { $("#btn").click(function () { var UserName = $("#UserName").val(); $.post("queryHandler.ashx", { "UserName": UserName }, function (data){ //console.log(data); var stu = data.stu; $("#tb").empty(); //如何把data显示在table上?要用DOM for (i = 0; i <stu.length; i++) { var html = "<tr><td>" + stu[i].UserId + "</td><td>" + stu[i].UserName + "</td><td>" + stu[i].Pwd + "</td></tr>"; $("#tb").append(html); } }, "json"); }); }); </script> </head> <body> <div id="nav"> 用户名:<input type="text" name="UserName" id="UserName" /> <input type="button" value="查询" id="btn" /> </div> <table> <thead> <tr> <td>UserId</td> <td>UserName</td> <td>Pwd</td> </tr> </thead> <tbody id="tb"></tbody> </table> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace AJAX { /// <summary> /// queryHandler 的摘要说明 /// </summary> public class queryHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string UserName = context.Request["UserName"]; string sql = "select UserId,UserName,Pwd from Users where UserName like '%"+@UserName+"%'"; SqlParameter p = new SqlParameter("@UserName",UserName); DataTable dt= SQLHelper.ExecuteDataTable(sql, p); var stu = "{\"stu\":["; for(int i=0; i < dt.Rows.Count; i++) { stu +="{ \"UserId\":\""+dt.Rows[i]["UserId"] + "\" ,\"UserName\":\"" + dt.Rows[i]["UserName"] + "\", \"Pwd\":\"" + dt.Rows[i]["Pwd"] + "\"}"; //最后一次循环不需要加逗号 if (i!= dt.Rows.Count - 1) { stu += ","; } } stu += "]}"; context.Response.Write(stu); } public bool IsReusable { get { return false; } } } }