zoukankan      html  css  js  c++  java
  • ajax操作json的三种方式

    一、 什么是json?

    1. JSON是一种轻量级的数据交换格式

    2. JSON 可以将 JavaScript 对象中表示的一组数据转换为字符串,然后就可以在网络或者程序之间轻松地传递这个字符串,并在需要的时候将它还原为各编程语言所支持的数据格式

    JSON最常用的格式是对象的 键值对。例如下面这样:
      {"firstName": "Brett", "lastName": "McLaughlin"}
     
    具体前台代码如下: 
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
        <script src="../Js/jquery-1.7.1.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#btnData").click(function () {
                    //$post需要四个参数,1. 请求的URL,2. 传递的参数,3. 返回的数据,4. 数据类型(参数4默认类型为text)
                    $.post("GetJson.ashx", {}, function (data) {
                        alert(data);
                        alert("用户名是:"+data.Name);
                    },"json");
                });
                $("#btnData1").click(function () {
                    $.post("GetJson.ashx", {}, function (data) {
                        var serverData = $.parseJSON(data);   //将获取的数据转换成json对象
                        alert("用户名是:" + serverData.Name);
                    });
                });
    
                $("#btnData222").click(function () {
                    $.getJSON("GetJson.ashx", {}, function (data) {    //getjson默认将获取的数据转换成json对象,所以不用加上面的parsejson,但是该请求只能用于get请求
                     
                        alert("用户名是:" + data.Name);
                    });
                });
            });
        </script>
    </head>
    <body>
        <input type="button" value="获取数据" id="btnData" />
          <input type="button" value="获取数据1111" id="btnData1" />
    
          <input type="button" value="获取数据2222" id="btnData222" />
    </body>
    </html>

    一般处理程序代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace CZBK.ItcastProject.WebApp._2015_6_3
    {
        /// <summary>
        /// GetJson 的摘要说明
        /// </summary>
        public class GetJson : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("{"Name":"zhangsan","Age":"12"}");
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
  • 相关阅读:
    BZOJ2219数论之神——BSGS+中国剩余定理+原根与指标+欧拉定理+exgcd
    Luogu 3690 Link Cut Tree
    CF1009F Dominant Indices
    CF600E Lomsat gelral
    bzoj 4303 数列
    CF1114F Please, another Queries on Array?
    CF1114B Yet Another Array Partitioning Task
    bzoj 1858 序列操作
    bzoj 4852 炸弹攻击
    bzoj 3564 信号增幅仪
  • 原文地址:https://www.cnblogs.com/wangjinya/p/10405782.html
Copyright © 2011-2022 走看看