AJAX json的应用

前台代码:

<script type="text/javascript">
        var xhr;
        window.onload = function () {
            xhr = new XMLHttpRequest();
            document.getElementById("btnAdd").onclick = AddData;
        }

        function AddData() {
            xhr.open("POST", "TestAjax.ashx", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = watching;//设置回调函数
            var txtname = document.getElementById("Text1").value;
            var txtage = document.getElementById("Text2").value;
            var txtjiguan = document.getElementById("Text3").value;
            var postStr = "name=" + txtname+ "&age=" + txtage+ "&txtjiguan=" + text3;
          xhr.send(postStr);
        }

 //回调函数
        function watching() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    var responsedata = xhr.responseText;
                    var jsonresponsedata = eval("("+responsedata+")");//转换成json对象
                        alert(jsonresponsedata.name+jsonresponsedata.age+jsonresponsedata.jiguan);
                    }

                }
            }
    </script>

//后台代码,新建一个一般处理程序

public class TestAjax : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string name = context.Request.Form["txtname"];
            string age = context.Request.Form["txtage"];
            string jiguan = context.Request.Form["txtjiguan"];
            context.Response.ContentType = "text/plain";
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"name\":\"" + name + "\",\"age\":\"" + age + "\",\"jiguan\":\"" + jiguan + "\"}");//json格式的数据
            context.Response.Write(sb);
         
        }

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

posted @ 2011-11-07 13:39  yxf2011  阅读(174)  评论(0编辑  收藏  举报