利用 JSON 對網頁傳值

JSON 是一種文字格式,用於描述資料的結構,包含兩種存在結構:

(1) 物件(Object):以 { } (大括號)作為開始與結束,每個名稱或是值之間使用,(逗號) 隔開。

(2) 陣列(Array):一個陣列是一個值(Value)的集合,以 [ ] (中括號) 作為開始與結束,值之間使用,(逗號) 隔開。

此範例為網頁上要傳資料給對方時,利用傳 JSON 的方式,將資料給對方,並存進對方資料庫。

先建立兩個不同的網頁,一頁為 JSON_Post,另一頁為 JSON_Read,JSON_Post 為畫面上的實作,並將傳送的

結果給 JSON_Read,一頁串 JSON,一頁接收,如圖:

假設一開始畫面上有三個可輸入的欄位,分別是姓名、密碼、年次,下方的 GridView 為資料庫中事先建立的幾筆資料,

按下查詢時,會帶出所有資料的 JSON 格式,並顯示在 "回傳JSON" 那邊,而按下 新增、修改、修改(JSON)按鈕時,

會將送出資料的結果一樣顯示在 "回傳JSON" 那部分,關於修改、修改(JSON)按鈕這兩個部分會再做說明。

一、JSON_Post 頁面內容

如上圖所示,在 JSON_Post 的頁面中,先設計好相關畫面,後端(.cs) 檔中程式碼撰寫如下:

(以北風資料庫作範例)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace FishTest
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection
        (ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //將資料呈現在GridView中
                conn.Open();
                string str = "";
                str = "select id,name,password,born from [FishTest].[dbo].[Pserson] ";
                SqlCommand cmd = new SqlCommand(str, conn);
                SqlDataReader sdr = cmd.ExecuteReader();

                DataTable dt = new DataTable();
                dt.Load(sdr);
                GridView1.DataSource = dt;
                GridView1.DataBind();

                cmd.Cancel();
                conn.Close();
            }
        }

        protected void search_Click(object sender, EventArgs e)
        {
            Stream writer = null;
            bool result = true;

            string strjson = "";
            strjson = "action=search";
            byte[] data = System.Text.Encoding.UTF8.GetBytes(strjson);
            string myResponseStr = "";

            //要求的對象網頁
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://localhost:3002/WebForm3.aspx");

            myRequest.Method = "POST";
            myRequest.Timeout = 300000;
            myRequest.ContentType = "application/x-www-form-urlencoded";
            System.Web.HttpUtility.UrlEncode(data);
            myRequest.ContentLength = data.Length;


            try
            {
                //發送並取得回應
                writer = myRequest.GetRequestStream();
                writer.Write(data, 0, data.Length);
                writer.Close();
            }
            catch (Exception)
            {
                result = false;
            }

            if (result)   //成功時讀取回應 
            {
                StreamReader swText = new StreamReader(
                        myRequest.GetResponse().GetResponseStream()
                        );
                //取得回應的XML字串
                myResponseStr = swText.ReadToEnd();
            }
            Label1.Text = myResponseStr;
            GridView1.DataBind();
        }

        protected void insert_Click(object sender, EventArgs e)
        {
            Stream writer = null;
            bool result = true;

            string strjson = "";
            strjson = "action=insert&name=" + name.Text + "&pwd=" + pwd.Text + "&year=" + year.Text;
            byte[] data = System.Text.Encoding.UTF8.GetBytes(strjson);
            string myResponseStr = "";

            //要求的對象網頁
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://localhost:3002/WebForm3.aspx");

            myRequest.Method = "POST";
            myRequest.Timeout = 300000;
            myRequest.ContentType = "application/x-www-form-urlencoded";
            System.Web.HttpUtility.UrlEncode(data);
            myRequest.ContentLength = data.Length;

            try
            {
                //發送並取得回應
                writer = myRequest.GetRequestStream();
                writer.Write(data, 0, data.Length);
                writer.Close();
            }
            catch (Exception)
            {
                result = false;
            }

            if (result)   //成功時讀取回應 
            {
                StreamReader swText = new StreamReader(
                        myRequest.GetResponse().GetResponseStream()
                        );
                //取得回應的XML字串
                myResponseStr = swText.ReadToEnd();
            }
            Label1.Text = myResponseStr;
            GridView1.DataBind();

        }

        protected void update_Click(object sender, EventArgs e)
        {
            Stream writer = null;
            bool result = true;

            string strjson = "";
            strjson = "action=update&name=" + name.Text + "&pwd=" + pwd.Text + "&year=" + year.Text;
            byte[] data = System.Text.Encoding.UTF8.GetBytes(strjson);
            string myResponseStr = "";

            //要求的對象網頁
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://localhost:3002/WebForm3.aspx");

            myRequest.Method = "POST";
            myRequest.Timeout = 300000;
            myRequest.ContentType = "application/x-www-form-urlencoded";
            System.Web.HttpUtility.UrlEncode(data);
            myRequest.ContentLength = data.Length;

            try
            {
                //發送並取得回應
                writer = myRequest.GetRequestStream();
                writer.Write(data, 0, data.Length);
                writer.Close();
            }
            catch (Exception)
            {
                result = false;
            }

            if (result)   //成功時讀取回應 
            {
                StreamReader swText = new StreamReader(
                        myRequest.GetResponse().GetResponseStream()
                        );
                //取得回應的XML字串
                myResponseStr = swText.ReadToEnd();
            }
            Label1.Text = myResponseStr;
            GridView1.DataBind();

        }

        protected void jsonupdate_Click(object sender, EventArgs e)
        {
            Stream writer = null;
            bool result = true;

            var json = new
            {
                name = name.Text,
                pwd = pwd.Text,
                year = year.Text,
            };

            string strjson = "";
            strjson = "action=jsonupdate&data=" + JsonConvert.SerializeObject(json);
            byte[] data = System.Text.Encoding.UTF8.GetBytes(strjson);
            string myResponseStr = "";

            //要求的對象網頁
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://localhost:3002/WebForm3.aspx");

            myRequest.Method = "POST";
            myRequest.Timeout = 300000;
            myRequest.ContentType = "application/x-www-form-urlencoded";
            System.Web.HttpUtility.UrlEncode(data);
            myRequest.ContentLength = data.Length;

            try
            {
                //發送並取得回應
                writer = myRequest.GetRequestStream();
                writer.Write(data, 0, data.Length);
                writer.Close();
            }
            catch (Exception)
            {
                result = false;
            }

            if (result)   //成功時讀取回應 
            {
                StreamReader swText = new StreamReader(
                        myRequest.GetResponse().GetResponseStream()
                        );
                //取得回應的XML字串
                myResponseStr = swText.ReadToEnd();
            }
            Label1.Text = myResponseStr;
            GridView1.DataBind();

        }

    }
}

其中在修改與修改(JSON)這兩者中,傳送資料是一樣的,只是在傳遞資料方法不一樣,但目的相同,使用 "修改" 時,

strjson 的部分為 strjson = "action=update&name=" + name.Text + "&pwd=" + pwd.Text + "&year=" + year.Text;

使用 "修改(JSON)" 時,strjson 的部分為 

var json = new
            {
                name = name.Text,
                pwd = pwd.Text,
                year = year.Text,
            };            
            strjson = "action=jsonupdate&data=" + JsonConvert.SerializeObject(json);

strjson 字串後方所接的,是代表網址列的參數,跨頁面傳遞資料可以用網址後面的參數或是json,當我在 JSON_Post 的頁面中按下

查詢時,strjson = "action=search",在 "回傳JSON" 那邊會顯示 JSON 格式的資料,或是我將 action=search 這段貼到 JSON_Read 頁面

後方的網址列,一樣可以得到 JSON 格式的資料,如圖:

JSON_Post:

JSON_Read :

二、JSON_Read 頁面內容

在 JSON_Read 頁面中,接收來自 JSON_Post 頁面的 JSON,並存進自己的資料庫中,程式碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Net;
namespace FishTest
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection
            (ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
        protected void Page_Load(object sender, EventArgs e)
        {
            string act = Request["action"], strjson = "";

            var json = new object();

            if (!string.IsNullOrEmpty(act) && act == "search")
            {
                string name = Request["name"];
                conn.Open();
                string sql = "select id,name,password,number,born,place from [FishTest].[dbo].[Pserson]";
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                conn.Close();

                if (dt.Rows.Count > 0)
                {
                    json = from data in dt.AsEnumerable()
                           select new
                           {
                               id = data.Field<int>("id"),
                               name = data.Field<string>("name"),
                               password = data.Field<string>("password"),
                               number = data.Field<string>("number"),
                               born = data.Field<string>("born"),
                               place = data.Field<string>("place")
                           };
                }
                else
                {
                    json = new
                    {
                        error = "無資料"
                    };
                }

                strjson = JsonConvert.SerializeObject(json);

                //回傳的是JSon格式的字串
                this.Response.Write(strjson);
                Response.End();
            }

            if (!string.IsNullOrEmpty(act) && act == "insert")
            {
                string name = Request["name"];
                string pwd = Request["pwd"];
                string year = Request["year"];

                SqlCommand insert = new SqlCommand("insert into [FishTest].[dbo].[Pserson] (name,password,born) values (@name,@pwd,@year)", conn);
                insert.Parameters.Add("@name", SqlDbType.NVarChar).Value = name;
                insert.Parameters.Add("@pwd", SqlDbType.NVarChar).Value = pwd;
                insert.Parameters.Add("@year", SqlDbType.NVarChar).Value = year;

                conn.Open();
                insert.ExecuteNonQuery();
                insert.Dispose();
                conn.Close();

                json = new
                {
                    state = "新增完成"
                };

                strjson = JsonConvert.SerializeObject(json);

                //回傳的是JSon格式的字串
                this.Response.Write(strjson);
                Response.End();
            }

            if (!string.IsNullOrEmpty(act) && act == "update")
            {
                string name = Request["name"];
                string pwd = Request["pwd"];
                string year = Request["year"];

                SqlCommand update = new SqlCommand("update [FishTest].[dbo].[Pserson] set password=@pwd,born=@year where name=@name", conn);
                update.Parameters.Add("@name", SqlDbType.NVarChar).Value = name;
                update.Parameters.Add("@pwd", SqlDbType.NVarChar).Value = pwd;
                update.Parameters.Add("@year", SqlDbType.NVarChar).Value = year;

                conn.Open();
                update.ExecuteNonQuery();
                update.Dispose();
                conn.Close();

                json = new
                {
                    state = "修改完成"
                };

                strjson = JsonConvert.SerializeObject(json);

                //回傳的是JSon格式的字串
                this.Response.Write(strjson);
                Response.End();
            }

            if (!string.IsNullOrEmpty(act) && act == "jsonupdate")
            {
                string data = Request["data"];

                JObject jo = JsonConvert.DeserializeObject<JObject>(data);

                SqlCommand update = new SqlCommand("update [FishTest].[dbo].[Pserson] set password=@pwd,born=@year where name=@name", conn);
                update.Parameters.Add("@name", SqlDbType.NVarChar).Value = jo["name"].ToString();
                update.Parameters.Add("@pwd", SqlDbType.NVarChar).Value = jo["pwd"].ToString();
                update.Parameters.Add("@year", SqlDbType.NVarChar).Value = jo["year"].ToString();
                conn.Open();
                update.ExecuteNonQuery();
                update.Dispose();
                conn.Close();

                json = new
                {
                    state = "修改完成"
                };


                strjson = JsonConvert.SerializeObject(json);

                //回傳的是JSon格式的字串
                this.Response.Write(strjson);
                Response.End();
            }
        }
    }
}

程式碼中的 Request 指的是接網址上的參數,所以像新增部分就做新增的Sqlcommand,修改部分就做修改的Sqlcommand;

所以此在前端HTML的部分並沒有設定相關的畫面,因為主要是後端來接收 JSON_Read 頁面所傳過來的資料。