关于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";
),但即使如此,如果服务端采取了编码措施,那么客户端接受到的将是纯文本!

原文地址:https://www.cnblogs.com/luoxiaonet/p/2061033.html