JQuery ajax json

來源:互聯網
上載者:User

序列化字元方法:注意這裡的引用“System.Runtime.Serialization”和“System.ServiceModel.Web
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Web;///記得引用這個命名空間
using System.IO;
using System.Text;

namespace BLL
{
    /// <summary>
    /// 序列化實體類
    /// </summary>
    public class JsonHelper
    {
        public JsonHelper()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        /// <summary>
        /// 把對象序列化 JSON 字串
        /// </summary>
        /// <typeparam name="T">物件類型</typeparam>
        /// <param name="obj">對象實體</param>
        /// <returns>JSON字串</returns>
        public static string GetJson<T>(T obj)
        {
            //記住 添加引用 System.ServiceModel.Web
            /**
             * 如果不添加上面的引用,System.Runtime.Serialization.Json; Json是出不來的哦
             * */
            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                json.WriteObject(ms, obj);
                string szJson = Encoding.UTF8.GetString(ms.ToArray());
                return szJson;
            }
        }

        /// <summary>
        /// 把JSON字串還原為對象
        /// </summary>
        /// <typeparam name="T">物件類型</typeparam>
        /// <param name="szJson">JSON字串</param>
        /// <returns>對象實體</returns>
        public static T ParseFormJson<T>(string szJson)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
                DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
                return (T)dcj.ReadObject(ms);
            }
        }
    }
}

實體類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Model
{
    public class jsonItem
    {
        public string UserName { get; set; }

        public string PWD { get; set; }
    }
}

調用方法:用反射方式,只需傳方法就可以執行
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Text;

namespace test.JQuery.json
{
    /// <summary>
    /// $codebehindclassname$ 的摘要說明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class json : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //反射的機制:只需要傳方法進來就可以執行方法、獲得資料。。
            if (context.Request["cmd"] != null)
            {
                string cmd = context.Request["cmd"];
                var method = this.GetType().GetMethod(cmd);
                if (method != null)
                {
                    method.Invoke(this, new object[] { context });
                }
            }
        }

        /// <summary>
        /// 序列化的Json字串
        /// </summary>
        public void GetInfo(HttpContext context)
        {
            Model.jsonItem item = new Model.jsonItem();
            Model.jsonItem item1 = new Model.jsonItem();
            List<Model.jsonItem> list = new List<Model.jsonItem>();
            item.UserName = "aaaa";
            item.PWD = "1111";
            list.Add(item);
            item1.UserName = "bbbb";
            item1.PWD = "2222";
            list.Add(item1);
            string strJson = BLL.JsonHelper.GetJson<List<Model.jsonItem>>(list);
            context.Response.Write(strJson);
        }

        /// <summary>
        /// 序列化的Json字串
        /// </summary>
        public void GetInfo1(HttpContext context)
        {
            Model.jsonItem item = new Model.jsonItem();
            Model.jsonItem item1 = new Model.jsonItem();
            List<Model.jsonItem> list = new List<Model.jsonItem>();
            item.UserName = "abc";
            item.PWD = "123";
            list.Add(item);
            item1.UserName = "bcd";
            item1.PWD = "234";
            list.Add(item1);
            string strJson = BLL.JsonHelper.GetJson<List<Model.jsonItem>>(list);
            context.Response.Write(strJson);

            //string output = string.Format("'UserName':'{0}','PWD':'{1}'", "cccc", "3333");
            //string output1 = string.Format("'UserName':'{0}','PWD':'{1}'", "dddd", "4444");
            //StringBuilder result = new StringBuilder();
            //result.AppendFormat("[{0}{1}{2},{3}{4}{5}]", "{", output, "}", "{", output1, "}");
            //context.Response.Write(result.ToString());
            //context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

html代碼調用:
<!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></title>

    <script src="http://imwujianhao.blog.163.com/blog/../jquery-1.4.2.js" type="text/javascript"></script>

    <script type="text/javascript" language="javascript">
        function BtnClick() {
            var uid = $("#Text1").val();
            var pwd = $("#Text2").val();
            $.ajax({
                url: "json.ashx",
                type: "POST",
                data: { cmd: "GetInfo", Password: pwd },
                beforeSend: loading,
                success: function(data) {
                    var json = eval(data); //eval("(" + data + ")");
                    $("#dd").empty(); //清除dd的資訊
                    $.each(json, function(idx, item) {
                        var user = item.UserName;
                        var pass = item.PWD;
                        $("#dd").append("<b>使用者名稱:" + user + " 密碼:" + pass + "</b>");
                    });
                }

            });
        }
        function loading() {
            $("#dd").html("<img src='http://imwujianhao.blog.163.com/blog/20-0.gif' />");
        }
        function BtnClick1() {
            $.ajax({
                url: "json.ashx",
                type: "POST",
                data: { cmd: "GetInfo1" },
                beforeSend: loading,
                success: function(data) {
                    //使用eval函數
                    var json = eval(data);
                    $("#dd").empty();
                    //因為上面為list集合
                    for (var i = 0; i < json.length; i++) {
                        $("#dd").append("<h3>使用者名稱:" + json[i].UserName + " 密碼:" + json[i].PWD + "</h3>");
                        //alert(json[i].Id + "Name:" + json[i].Name);
                    }
                }

            });
        }
    </script>

</head>
<body>
    <div>
        <input type="text" name="Text1" id="Text1" /><br />
        <input type="text" name="Text2" id="Text2" />
        <br />
        <input type="button" id="btn1" value="事件1" onclick="BtnClick()" />
        <input type="button" id="Button1" value="事件2" onclick="BtnClick1()" />
    </div>
    <div id="dd">
        sd
    </div>
</body>
</html>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.