Json一般用在少量的数据处理。因为格式简单,操作方便,而且javascript本事就支持Json格式的处理功能。所以建议大家使用
Json一般格式如下:{"id":"1","name":"abc"}或者[{"id":"1","name":"abc"},{"id":"1","name":"abc"}]
下面是js中几种解释Json格式的方法:
eval('('+Json+')')
- 1.
为什么这样写:主要是因为在JavaScript中,表达式语句不允许以左花括号”{“开始,如果这样做,会与块语句产生混淆.在使用eval()解析JSON文本时,为了解决这个问题,就需要加上圆括号.圆括号作为分组运算符,可以对包围在其中的表达式求职.
var strJSON= (new Function("return " + Json))();
- 1.
通过创建方法的方式解释Json
var strJSON= JSON.parse(Json);
- 1.
注意:这种方法能够解释的Json格式必须键值对都要加双引号,不然解释不了Json格式
实例
Json.aspx页面
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Json.aspx.cs" Inherits="web.javascript.Json.Json" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="div1">
</div>
<input type="button" id="btn" value="but" />
</form>
<script type="text/javascript" src="http://www.cnblogs.com/script/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
// 异步处理Json对象
$("#btn").click(function() {
$.ajax({
url: "Json.ashx",
type: "post",
data: { id: "123" },
datatype: "Json",
success: function(data) {
var strData = data;
alert("1-----------");
var str1 = eval("(" + data + ")"); // ***种js解释Json
alert("2-----------");
var str2 = (new Function("return " + strData))(); // 第二种js解释Json
alert(str2.id + " @ " + str2.name);
alert("3-----------");
var str3 = JSON.parse(strData);
alert(str3.id + " @ " + str3.name);
// 处理多维Json
var strSs = "";
alert(str1.length);
for (var i = 0; i <str1.length; ++i) {
strSs += str1[i].id + "@" + str1[i].name + " ";
}
alert(strSs);
},
error: function(xhr, data, ts) {
alert(data);
}
});
});
</script>
</body>
</html>
Json.ashx处理程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace web.javascript.Json
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Json1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
// 多维
string strJSONs = "[{\"id\":1,\"name\":\"11\"},{\"id\":2,\"name\":\"22\"},{\"id\":3,\"name\":\"33\"}]";
// 一维
//string strJSONs={\"id\":\"123\",\"name\":\"qwe\"}
context.Response.Write(strJSONs);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
以上是本人在实际项目中的总结,希望对大家有帮助,同时也希望大家多多指点。
本文地址:http://www.cnblogs.com/snakeraining/archive/2012/03/26/2418519.html
【编辑推荐】