最近在做一个网站项目时,有异步请求的需求,经过一番查找资料,终于实现了这个部分,在此记录一下,以备日后回顾.
1.jQuery的ajax函数可以很方便的建立发起异步请求
$(".drop-a").click(function () { var content = $(this).next("div"); if (isGet == false) { var code = $("#code").html(); var data = { code: code, table: "acount" }; $.ajax({ type: "POST", url: "../response/getinfo.ashx", data: data, dataType: "text", success: function (msg) { //$("#ajax").append(msg); alert(msg); isGet = true; } }); }
本示例调用../response/getinfo.ashx(一般处理程序)
2.getinfo.ashx内容
public void ProcessRequest(HttpContext context) { string code = context.Request["code"]; string table = context.Request["table"]; string sql = string.Format("select * from `{0}` where `{1}` = ‘{2}‘", table, "code", code); DataTable getTable = BasicQuery.ExecuteDataTable(sql); //调用MYSQL查询函数 string json = JsonConvert.SerializeObject(getTable);//将Object转化为json文本 context.Response.ContentType = "text/plain"; context.Response.Write(json);//响应输出json文本 }
getinfo.ashx内容
接收code和表名作为参数查询数据库,并响应输出一段字符串(json文本)
3.JQuery.ajax处理返回的json数据
$.ajax({ type: "POST", url: "../response/getinfo.ashx", data: data, dataType: "text", success: function (msg) { //$("#ajax").append(msg); //alert(msg); var json = $.parseJSON(msg); var html = ""; html += "<p>ID:" + json[0].ID; html += "</p><p>Code:" + json[0].Code; html += "</p><p>Name:" + json[0].Name; html += "</p><p>Phone:" + json[0].Phone; html += "</p><p>Mail:" + json[0].Mail; html += "</p>"; content.html(html); isGet = true; } });
处理返回的json字符串
在这段代码中,首先将返回的json字符串转化为对象(数组),然后根据返回数据的内容解析出需要的信息,并加载到网页中.
时间: 2024-11-09 12:38:01