• 关于JSON的使用记录


    第一步,【服务端】:定义为 json格式

    context.Response.ContentType = "json/application;charset=utf-8";
    context.Response.ExpiresAbsolute
    = DateTime.Now.AddDays(-1);
    context.Response.AddHeader(
    "pragma", "no-cache");
    context.Response.AddHeader(
    "cache-control", "");
    context.Response.CacheControl
    = "no-cache";
    context.Response.Charset
    = Encoding.UTF8.ToString();

    第二步,【客户端】:dataType类型为json。

    jQuery.ajax({
    type:
    "get",
    dataType:
    "json",
    contentType:
    "application/x-www-form-urlencoded; charset=UTF-8",
    url: loadTreeUrl,
    data: {
    "loadFacility" : "LoadFacilityVehicle",
    "date" : new Date()
    },
    complete :
    function(msg){
    },
    ajaxComplete :
    function(msg){

    },
    success:
    function(originalData) {

    var treeData = {
    showcheck:
    true,
    theme:
    "bbit-tree-lines",
    data: originalData
    };

    $("#tree").treeview(treeData);
                  },
    //end Success
    error: function(XMLHttpRequest, textStatus, errorThrown){
    alert(
    "status_" + XMLHttpRequest.status);
    alert(
    "readyState_" + XMLHttpRequest.readyState);
    alert(
    "textStatus_" + textStatus);
    //$.ligerDialog.alert(XMLHttpRequest.responseXML.childNodes[1].text,"警告信息","warn");
    } //end error
    }); //end Ajax

    但是,当服务端传递的字符串经过编码处理后,情况就糟糕了:

    【服务端】:编码

    using Microsoft.JScript;
    string finalData = Microsoft.JScript.GlobalObject.escape(sbTreeData.ToString());

     【客户端】:到了客户端,势必要解码,否则我们是看不懂的。

    success: function(originalData) {
    var finalData = unescape(originalData);
    var treeData = {
    showcheck:
    true,
    theme:
    "bbit-tree-lines"
    };

    //采用 eval将纯文本转换为 JSON对象。

      treeData.data = eval("("+ finalData +")");
    $("#tree").treeview(treeData);

    },
    //end Success

     很显然,我们需要 eval()的帮忙才可以。否则插件接收到的将是纯文本,导致报错。

     结论:要保证两端的数据类型一致,比如都是纯文本(text/plain)或JSON(context.Response.ContentType = "json/application;charset=utf-8";
    ),但即使如此,如果服务端采取了编码措施,那么客户端接受到的将是纯文本!

  • 相关阅读:
    [LeetCode] 500. Keyboard Row 键盘行
    [LeetCode] 502. IPO 上市
    [LeetCode] 495. Teemo Attacking 提莫攻击
    [LeetCode] 655. Print Binary Tree 打印二叉树
    [LeetCode] 654. Maximum Binary Tree 最大二叉树
    [LeetCode] 637. Average of Levels in Binary Tree 二叉树的层平均值
    Dubbo 在maven项目中的应用
    前后端分离springmvc和RESTful理解
    一个相对通用的JSON响应结构,其中包含两部分:元数据与返回值
    MAC OS查看端口占用情况及杀死进程
  • 原文地址:https://www.cnblogs.com/luoxiaonet/p/2061033.html
Copyright © 2020-2023  润新知