lijinchang

导航

利用jquery实现Ajax并用json2.js对返回的json进行转换操作

前端代码

 

<script src="jquery-1.7.1.js" language="javascript" type="text/javascript"></script>
    <script src="JS/json2.js" language="javascript" type="text/javascript"></script>
    <script  language="javascript" type="text/javascript">
    $(document).ready(function()
    {
      $.post('Handler1.ashx',{name:'lijc',sex:'nan'},function(data){
      var jsonstr=JSON.stringify(data);//把object转换成json字符串
      var jsonobj=JSON.parse(jsonstr);//把json字符串转换成object
      jsonobj=$.parseJSON(jsonstr);//把json字符串转换成object的另一种方式
      alert(jsonstr);
      $.each(data,function(key,item){
        alert(item.name);
      }
      );
      },'json');
});
</script>

 

 

后台一般处理程序

 

 string name1 = context.Request["name"].ToString();
            string sex = context.Request["sex"].ToString();
            product p = new product();
            p.id = 1;
            p.name = name1;
            p.price = 12.1;
            p.productinfor = "productinfor";
            p.date = DateTime.Now;
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List<product> list = new List<product>();
            list.Add(p);
            p.productinfor = "infor1";
            list.Add(p);
            string json2 = serializer.Serialize(list);
            string json = serializer.Serialize(p);

            p = serializer.Deserialize<product>(json);
            list = serializer.Deserialize<List<product>>(json2);
          

            context.Response.Write(json2);

 

如果不是用json2.js 而是用<script src="JS/jquery.json-2.3.js" type="text/javascript"></script>

 

则object专程json字符串的函数还可以写成$.toJSON(obj);

 

$.post("Handler1.ashx",{name:'name',sex:'nan'},function(data){
    var comment = {};
    comment.parentId = 1;
    comment.content = 'test';
    var a1=$.toJSON(comment);//object转化成jsonstr
    alert(a1);
    var last=JSON.stringify(comment); //object转化成jsonstr的另一种方式
    alert(last);
    var l=$.parseJSON(last);//jsonstr转化成object的一种方式
    alert(l.content);
    alert(a1);
    var obj = JSON.parse(a1); //jsonstr转化成object的另一种方式
    alert($.toJSON(data));
      var str=null;
      $.each(data,function(id,it){
       alert(it.name);
       str+='name:'+it.name+',price:'+it.price;
      });
      alert(str);
    },'json');

posted on 2012-01-16 16:41  lijinchang  阅读(4123)  评论(0编辑  收藏  举报