Js解析Json字符串

来源:互联网 发布:python redis 库 编辑:程序博客网 时间:2024/05/16 05:43

下面代码生成一个Json字符串


using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace WebApplication.handle {    /// <summary>    /// JsonHandler 的摘要说明    /// </summary>    public class JsonHandler : IHttpHandler {        public void ProcessRequest(HttpContext context) {            context.Response.ContentType = "text/plain";            string name = "admin";            string hello = "hello";            string json = "[{\"name\":\"" + name + "\"},{\"name\":\"" + hello  + "\"}]";            context.Response.Write(json);        }        public bool IsReusable {            get {                return false;            }        }    }}


    <script type="text/javascript" src="/js/jquery-1.11.2.js"></script>    <script type="text/javascript">        function load() {            $.ajax({                url: "/handle/JsonHandler.ashx",                dataType: "json",                success: function (data) {                    var obj = eval(data);                    alert(obj[0].name);                }            });        }    </script>

说明 : 返回的数据类型 必须是 json  不可以是text 类型 如上面代码所示 也就是dataType 

js 解析json 字符串 用eval()函数就可以了 如果解析失败 多半 json 字符串格式有问题 



0 0