Json 备忘录
最近项目上的一个页面比较复杂,多次用到Json提交数据,顺便记录下来,以便以后查询.
js代码:
<script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script src="Scripts/json2.js" type="text/javascript"></script>
<title></title>
<script type="text/javascript">
function onSubmit() {
var employee = {
Name: "chenxizhang",
Country: "China",
Orders: [
{ OrderID: 10248 },
{ OrderID: 10249 }
]
};
//debugger;
var testArrayJson = [];
var testJson;
var table = $("#tableJson")[0];
for (var i = 0; i < table.rows.length; i++) {
var temp = { //在此生成Json对象
Name: table.rows[i].cells[0].innerText,
Country: table.rows[i].cells[1].innerText,
Orders: [
{ OrderID: table.rows[i].cells[2].innerText }
]
};
testJson += JSON.stringify(temp) + ","; //把所有Json对象转成字符串
}
testJson = "[" + testJson.substring(0, testJson.length - 1).replace('undefined', '') + "]";//组合json对象
testArrayJson = eval('(' + testJson + ')'); //使用Eval转换为Json对象
//发送POST请求,数据也是json格式。但数值部分需要转换为字符串
$.post("Ajax.aspx", { data: JSON.stringify(testArrayJson) }, function (result) {
//alert(result);
var r = JSON.parse(result);
alert(r.Message);
});
}
</script>
页面代码:
<input type="button" value="Submit" onclick="onSubmit();" />
<table id="tableJson">
<tr>
<td>
test1
</td>
<td>
China
</td>
<td>
123
</td>
</tr>
<tr>
<td>
test2
</td>
<td>
China
</td>
<td>
456
</td>
</tr>
<tr>
<td>
test3
</td>
<td>
China
</td>
<td>
789
</td>
</tr>
</table>
本实例是用js遍历table 取出每行的属性或列值.组成json对象,发送到Ajax.aspx页面进行处理.
Ajax.aspx 处理部分.(页面部分除了第一行服务器标记外一定要删除)
protected void Page_Load(object sender, EventArgs e)
{
try
{
var ser = new DataContractJsonSerializer(typeof(Employee[]));
var data = Request["data"];
var ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
var emp = (Employee[])ser.ReadObject(ms);
ms.Close();
//此时已经得到了相应的Employee实例,可以进行服务器端的处理
var ser2 = new DataContractJsonSerializer(typeof(ActionResult));
var ms2 = new MemoryStream();
var result = new ActionResult() { Code = 200, Message = emp[0].Name+ emp[0].Country };
ser2.WriteObject(ms2, result);
ms2.Position = 0;
var buffer = new byte[ms2.Length];
ms2.Read(buffer, 0, buffer.Length);
ms2.Close();
Response.Write(Encoding.UTF8.GetString(buffer));
}
catch()
{
}
}
以下是定义的服务器端实体类:
public class Employee
{
public string Name { get; set; }
public string Country { get; set; }
public OrderItem[] Orders { get; set; }
}
public class OrderItem
{
public int OrderID { get; set; }
}
public class ActionResult
{
public int Code { get; set; }
public string Message { get; set; }
}