c#后台将数据转换为json字符串,前台ajax解析json字符串

 
public partial class ShowMsg
    {
        public string FromUserImg { get; set; }
        public string Message { get; set; }
        public string MessageType { get; set; }
    }

 
  
[WebMethod]
    //得到缓冲的消息
    
    public static string GetBufferText(string Touser, string Fromuser)
    {
        OCEntities oc = new OCEntities();
        List msgList = new List();//PrivateMsg是一个类,转到定义可显示其成员
        SqlConnection Con = SQLhelper.CreateConnection();
        SqlCommand CmdObj;
        SqlDataReader reader;
        int FromUid = int.Parse(Fromuser);
        var ToUid = oc.Users.Where(p => p.Uusername == Touser).FirstOrDefault().Uid;
        string sql = "select FromUid,ToUid,Message,MessageType from  PrivateMsg  where (FromUid=" + FromUid + " and ToUid=" + ToUid + ") or (FromUid=" + ToUid + " and ToUid=" + FromUid + ") and DateDiff(day,MessageTime,getdate())<=3 order by MessageTime";
        CmdObj = new SqlCommand(sql, Con);
        Con.Open();
        reader = CmdObj.ExecuteReader(CommandBehavior.CloseConnection);
        while (reader.Read())
        {
            var FromUserImg = oc.Users.Where(p => p.Uid == FromUid).FirstOrDefault().Uphoto;
           // var ToUserImg = oc.Users.Where(p => p.Uid == int.Parse(reader["ToUid"].ToString())).FirstOrDefault().Uphoto;
            ShowMsg msg = new ShowMsg { FromUserImg = FromUserImg, Message = reader["Message"].ToString(), MessageType = reader["MessageType"].ToString() };
            msgList.Add(msg);
        }
        reader.Close();
        return  JsonConvert.SerializeObject(msgList);//将PrivateMsg转换为json字符串
    }

先定义类ShowMessage,其中有三个成员变量,在GetBufferText方法中新建List msgList,将数据库中查出的数据添加到msgList,用JsonConvert将其转化为

json字符串,注意是json字符串,传到前台是还需要转化为json对象

[WebMethod]是前台ajax调用的方法,即GetBufferText,参数为ToUser与FromUser.

前台代码

 $.ajax({
                type: "Post",
                url: "WebChat.aspx/GetBufferText",
                contentType: "application/json; charset=utf-8",
                data: "{'Touser':'" + Touser + "','Fromuser':"+uid+"}",
                dataType: "json",
                success: function (data) {
                    //alert(data.d)
                    var json = $.parseJSON(data.d);
                    var show = "";
                    $.each(json, function (index, item) { //循环获取数据 
                        var FromUserImg = json[index].FromUserImg;
                       // alert(FromUserImg)
                      //  var ToUserImg = json[index].ToUserImg;
                        var Message = json[index].Message;
                        var MessageType = json[index].MessageType;//消息类型是"0",代表用户发出的消息。"1"代表用户收到的消息
                        show += "
" + Message + "
"; }); $("#chatbuffer").html(show); }, error: function (err) { alert("错误信息"); } });

data.d为后台传来的json字符串,用$.parseJSON将其转换为json对象,然后访问其中的数据。

你可能感兴趣的:(c#后台将数据转换为json字符串,前台ajax解析json字符串)