handler.ashx
代码
<%@ webhandler language="c#" class="handler" %> using system; using system.web; using system.data; using system.text; public class handler : ihttphandler { public void processrequest (httpcontext context) { /*context.response.contenttype = "text/plain"; string data = "[{name:\"fan\",age:26},{name:\"wang\",age:25}]";//构建的json数据 context.response.write(data);*/ dataset ds = new dataset(); datatable dt = new datatable(); dt.columns.add("name", typeof(string)); dt.columns.add("year", typeof(string)); dt.columns.add("avg", typeof(string)); datarow tr = dt.newrow(); tr["name"] = "张三"; tr["year"] = "2005-02-02"; tr["avg"] = "男"; dt.rows.add(tr); //ds.tables.add(dt); datarow tr2 = dt.newrow(); tr2["name"] = "李四"; tr2["year"] = "2007-02-02"; tr2["avg"] = "女"; dt.rows.add(tr2); ds.tables.add(dt); context.response.clear(); context.response.contentencoding = encoding.utf8; context.response.contenttype = "application/json"; //response.write("{\"success\":true,\"name\":\"张三\",\"year\":\"2009-12-12\"}"); context.response.write(getjson(ds)); context.response.flush(); context.response.end(); } public bool isreusable { get { return false; } } private static string getjson(dataset ds)//这里调用了json帮助文件,jsonhelp.cs 就不放出源码了 { json.jsonhelper jsonhelp = new json.jsonhelper(); jsonhelp.success = true; //jsonhelp.totlalcount = getprjlistcount(); jsonhelp.totlalcount = ds.tables[0].rows.count; foreach (datarow dr in ds.tables[0].rows) { jsonhelp.additem("name", dr["name"].tostring()); jsonhelp.additem("avg", dr["avg"].tostring()); if (dr["year"] != dbnull.value) { jsonhelp.additem("year", convert.todatetime(dr["year"]).tostring("yyyy/mm/dd")); } else { jsonhelp.additem("year", string.empty); } jsonhelp.itemok(); } string strresult = jsonhelp.tostring(); return strresult; } }
test.aspx
代码
<script src="js/jquery.js" type="text/javascript" language="javascript"></script> <script type="text/javascript"> $(function(){ $.getjson("handler.ashx",function(json){ $.each(json.data,function(i){$('#content').append("姓名:"+json.data[i].name+"----性别:"+json.data[i].avg+"----时间:"+json.data[i].year+"<br/>");}); }); }); </script> <body> <form id="form1" runat="server"> <p id="content"></p> </form> </body>
把handler.ashx文件内容放入普通aspx文件page_load方法中同样适用
即$.getjson(ssss.aspxfunction(e){});
以上就是jquery $.getjson 与.net 结合用法推荐的详细内容。
