jQuery+JSON 的使用范例

今天一整天都在使用JSON,用到頭昏眼花


看了一堆前人的code,然後使用我最擅長的Copy and Paste大法


剛開始不去抓資料庫資料,還算順利,一下就出現結果


可是呢,當我需要開始撈自己資料庫時,卻一直像鬼打牆般的資料出不來


後來最後弄到下午,終於發現自己的笨點  --"Key"錯字.......囧rz


果然,寫Code 或是研究Code時還是得小心一點,不然常常會死在不該死的地方


參考範例:


http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback


以下就是我的Code


這一頁是使用jQuery+JSON去 test.aspx 頁取得資料的方法


test.htm


<!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>
    <title>取得
JSON內資料</title>
    <script type="text/javascript"
src="js/jquery-1.2.6.pack.js"></script>
    <script
type="text/javascript">
       //在page
load的時候執行

        $(document).ready(function() {
               
Getdata();
        });
       
        function Getdata()
       
{
            //jQuery裡面的方法  --$.getJSON
===>jQuery.getJSON( url, [data], [callback] )

           

            $.getJSON("test.aspx?id=123",
               
function(data){
                    $("#test").append("price :"+data.price+
'<br />');
                    $.each(data.items,
function(i,item){
                    $("#test").append(item.name + ' / ' +
item.title + ' / ' + item.price+ ' / ' + item.content  + '<br
/>');
                   
                  });
               
});
        }
   
</script>
</head>
<body>
<div
id="test"></div>
</body>
</html>

接下來就是抓資料庫的部分


json.aspx


在頁面部分,把所有HTML tag都清空,只留下


<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="json.aspx.cs" Inherits="json" %>


然後在json.aspx.cs裡面去抓資料庫資料


protected void Page_Load(object sender, EventArgs e)
    {
        if
(Request["ID"].ToString() != null || Request["ID"].ToString() != "")
       
{


            //取得變數ID
           
string GroupTypeID = Request["ID"].ToString();


            //下面就是讀出資料庫裡面資料,這裡請自行處理
            string
StartDate =
ConfigurationManager.AppSettings["StartDate"].ToString();
            string
EndDate = ConfigurationManager.AppSettings["EndDate"].ToString();
           
MyClass.Data tt = new MyClass.Data();
            DataSet ds =
tt.GroupBasicData_GetData_ByGroupTypeID(GroupTypeID, StartDate, EndDate);


            //最後就是把撈出來的JSON字串Response.Write出來
           
Response.Write(CreateJsonParameters(ds.table[0]));
        }

    }



    /// <summary>
    ///
將DataTable轉變為JSON字串
    /// </summary>
    /// <param
name="dt">DataTable</param>
    ///
<returns></returns>

    public static string
CreateJsonParameters(DataTable dt)
    {
       /**/
        /*
/****************************************************************************
       
* Without goingin to the depth of the functioning of this Method, i will try to
give an overview
        * As soon as this method gets a DataTable it starts
to convert it into JSON String,
        * it takes each row and in each row
it grabs the cell name and its data.
        * This kind of JSON is very
usefull when developer have to have Column name of the .
        * Values Can
be Access on clien in this way. OBJ.HEAD[0].<ColumnName>
        *
NOTE: One negative point. by this method user will not be able to call any cell
by its index.
        *
*************************************************************************/

       
StringBuilder JsonString = new StringBuilder();
        //Exception
Handling
        if (dt != null && dt.Rows.Count > 0)
       
{
            JsonString.Append("{ ");
           
JsonString.Append("\"items\":[ "); //這裡 items
需要與前面接收的做對應

            for (int i = 0; i < dt.Rows.Count;
i++)
            {
                JsonString.Append("{
");
                for (int j = 0; j < dt.Columns.Count;
j++)
                {
                    if (j < dt.Columns.Count -
1)
                    {
                        JsonString.Append("\"" +
dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() +
"\",");
                    }
                    else if (j ==
dt.Columns.Count - 1)
                    {
                       
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" +
dt.Rows[i][j].ToString() + "\"");
                    }
               
}
                /**/
                /*end Of
String*/
                if (i == dt.Rows.Count - 1)
               
{
                    JsonString.Append("} ");
               
}
                else
                {
                   
JsonString.Append("}, ");
                }
            }
           
JsonString.Append("]}");
            return JsonString.ToString();
       
}
        else
        {
            return null;
        }
   
}



大功告成,然而JSON的字串格式長怎樣?

posted on 2011-05-14 18:55  人在程序  阅读(371)  评论(0编辑  收藏  举报

导航