none
JSON is undefined

    Question

  • 1.JsonTest.ashx

            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";

                List<Person> list = new List<Person>();
                list.Add(new Person { Name = "yzk", Age = 32" });
                list.Add(new Person { Name = "tom", Age = 12" });
                list.Add(new Person { Name = "lily", Age = 18 });
                JavaScriptSerializer jss = new JavaScriptSerializer();
                string json = jss.Serialize(list);
                context.Response.Write(json);
            }

    2.jsonTest.html

    <script type="text/javascript" src="/js/ajax.js"></script> 

    function LoadComments() {
           ajax("JsonTest.ashx", function (resTxt) {
                alert(resTxt);
                var p = JSON.parse(resTxt);
                            alert("name:" + p.Name + ";age:" + p.Age);

            });
        }

    3.ajax.js

    function ajax(url, onsuccess)
    {
        var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); 
        xmlhttp.open("POST", url, true); 

        xmlhttp.onreadystatechange = function ()
        {
            if (xmlhttp.readyState == 4) 
            {
                if (xmlhttp.status == 200) 
                {
                    onsuccess(xmlhttp.responseText);
                }
                else
                {
                    alert("AJAX error!"+xmlhttp.status);
                }
            }
        }
      
        xmlhttp.send();
    }

    4.problem

    2.jsonTest.html:alert("name:" + p.Name + ";age:" + p.Age);

    p.Name is undefined

    p.Age is undefined

    • Moved by litdev Sunday, March 15, 2015 12:46 PM
    Sunday, March 15, 2015 7:32 AM

Answers

All replies