最近的項目開始要用到JQuery了,可是我JQuery用的好少,作了一個簡單的經過Ajax和後臺交換數據的demo,預先練習下。javascript
主要是用AJAX調用後臺的方法 url: "Default.aspx/GetJosnData", 即頁面/方法,方法必須加上[WebMethod],而後返回Josn,而後前臺解析。html
[WebMethod]java
命名空間 System.Web.Services;jquery
向使用 ASP.NET 建立的 XML Web services 中的某個方法添加此特性後,就能夠從遠程 Web 客戶端調用該方法。ajax
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <title></title> <script type="text/javascript" language="javascript"> function showData() { $.ajax({ type: "post", url: "Default.aspx/GetJosnData", datatype: "json", contentType: "application/json; charset=utf-8", success: function (data) { var obj = (eval('(' + data.d + ')')[0]).JosnData; //循環Josn $.each(obj, function (i, item) { //i 序號,item對應的對象 $("#tab1").append("<tr><td> " + i + "</td><td>" + item.ID + " </td><td>" + item.Name + " </td></tr>"); }); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown); } }); } </script> </head> <body> <form id="form1" runat="server"> <div> <table id="tab1"> <tr> <td> 編號 </td> <td> ID </td> <td> Name </td> </tr> </table> <input id="Button1" type="button" value="查詢" onclick="showData()" /> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Services; using System.Data; using System.Text; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static string GetJosnData() { string Josn = ""; //先隨便構造一個Table DataTable dt = new DataTable(); dt.Columns.Add("ID"); dt.Columns.Add("Name"); for (int i = 0; i < 3; i++) { DataRow dr = dt.NewRow(); dr["ID"] = "編號" + i.ToString(); dr["Name"] = "值" + i.ToString(); dt.Rows.Add(dr); } //將DataTable轉換成Josn Josn = DataTableToJson("JosnData", dt); return Josn; } /// <summary> /// 將DataTble轉爲Josn數據 /// </summary> /// <param name="jsonName">Josn名</param> /// <param name="dt">須要轉換的DataTble</param> /// <returns></returns> public static string DataTableToJson(string jsonName, DataTable dt) { StringBuilder Json = new StringBuilder(); Json.Append("[{\"" + jsonName + "\":["); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { Json.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + dt.Rows[i][j].ToString() + "\""); if (j < dt.Columns.Count - 1) { Json.Append(","); } } Json.Append("}"); if (i < dt.Rows.Count - 1) { Json.Append(","); } } } Json.Append("]}]"); return Json.ToString(); } }