json的调用
WebService
[WebMethod] public string GetCategory() { SqlConnection conn = new SqlConnection("server=.;database=Holpe_Info;uid=sa;pwd=123;"); DataTable dt = new DataTable(); dt.TableName = "t_Category"; SqlDataAdapter sda = new SqlDataAdapter("SELECT Category_Name FROM Item_T_Info_Category WHERE Category_ParentID=1", conn); sda.Fill(dt); string str = DataTable2Json(dt); return str; } private string DataTable2Json(DataTable dt) { StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.Append("{/""); jsonBuilder.Append(dt.TableName); jsonBuilder.Append("/":["); for (int i = 0; i < dt.Rows.Count; i++) { jsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { jsonBuilder.Append("/""); jsonBuilder.Append(dt.Columns[j].ColumnName); jsonBuilder.Append("/":/""); jsonBuilder.Append(dt.Rows[i][j].ToString()); jsonBuilder.Append("/","); } jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("},"); } jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("]"); jsonBuilder.Append("}"); return jsonBuilder.ToString(); }
HTML
<pre class="html" name="code"><script type="text/javascript"> $(function(){ $("#button1").click(function(){ $.ajax({ type: "Post", dataType: "json", contentType:"application/json;utf-8", url: "WS1.asmx/GetCategory", data:"{}", success: function(data){ //json //var jsontext = '{"man":{"weight":"75kg","age":"24"},"ar":["1","2","3","4"]}'; //解析json var aman = eval("("+data.d+")"); //取出json中的信息 for(var i=0;i<aman.t_Category.length;i++) { alert(aman.t_Category[i].Category_Name); } } }); }) }) </script></pre>