json是一种简单的数据格式,比xml更轻巧。json是JavaScript 的原生格式,这意味着在 JavaScript 中处理json格式的 数据不需要任何特殊的API 或工具包。json的语法规则其实很简单:对象是一个无序的“‘名称/值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间使用“,”(逗号)分隔。看个例子先:上面的定义方式看起来很简单,但是如果字段众多,命名方式混杂,出错的概率大大增加,怎么办?这时候你就会想到用程序的方式生成json数据。json提供了json.js包,专门提供了几种常用的json处理函数。下载下来, ,将其引入然后就可以简单的使用object.toJSONString()转换成json数据。看代码:
Code
function testJson() {
//定义一个user(json的格式,其实就是定义一个js函数(变量)的方式而已)
var user =
{
"username": "jeff wong",
"age": 25,
"info": { "tel": "12345678", "cellphone": "13312345678" },
"address": // 数组
[
{ "city": "beijing", "postcode": "101110" },
{ "city": "ny city", "postcode": "911119" }
]
}
alert(user.username);
alert(user.age);
alert(user.info.cellphone);
alert(user.address[0].city);
alert(user.address[0].postcode);
user.username = "xiao wang";
alert(user.username);
}
function testJson() {
//定义一个user(json的格式,其实就是定义一个js函数(变量)的方式而已)
var user =
{
"username": "jeff wong",
"age": 25,
"info": { "tel": "12345678", "cellphone": "13312345678" },
"address": // 数组
[
{ "city": "beijing", "postcode": "101110" },
{ "city": "ny city", "postcode": "911119" }
]
}
alert(user.username);
alert(user.age);
alert(user.info.cellphone);
alert(user.address[0].city);
alert(user.address[0].postcode);
user.username = "xiao wang";
alert(user.username);
}
Code
function Car(maker, model, year, color) {
this.maker = maker;
this.model = model;
this.year = year;
this.color = color;
}
function testJson() {
var tempCar = new Car("VW", "S", 1999, "yellow");
alert(tempCar.toJSONString());
}
也可以使用eval或者parseJSON()方法来转换json数据到object:
function Car(maker, model, year, color) {
this.maker = maker;
this.model = model;
this.year = year;
this.color = color;
}
function testJson() {
var tempCar = new Car("VW", "S", 1999, "yellow");
alert(tempCar.toJSONString());
}
Code
function testJson() {
var str = '{ "name": "jeff wong", "age": 25,"address":"beijing"}';
var tempObj = eval('(' + str + ')');
alert(tempObj.toJSONString()); //使用eval方法
var tempObj1 = str.parseJSON();
alert(tempObj1.toJSONString()); // 或者使用parseJSON()方法
}
关于json.js的学习,请参考网上其他资源,这里我不再赘述了。说了这么多,实践环节开始了:
function testJson() {
var str = '{ "name": "jeff wong", "age": 25,"address":"beijing"}';
var tempObj = eval('(' + str + ')');
alert(tempObj.toJSONString()); //使用eval方法
var tempObj1 = str.parseJSON();
alert(tempObj1.toJSONString()); // 或者使用parseJSON()方法
}
ajax利用json发送/接收数据:
Code
// 此函数等价于document.getElementById /document.all
function $(s) { if (document.getElementById) {
return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }
// 创建 XMLHttpRequest对象,以发送ajax请求
function createXMLHTTP() {
var xmlHttp = false;
var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
"Microsoft.XMLHTTP"];
for (var i = 0; i < arrSignatures.length; i++) {
try {
xmlHttp = new ActiveXObject(arrSignatures[i]);
return xmlHttp;
}
catch (oError) {
xmlHttp = false; //ignore
}
}
// throw new Error("MSXML is not installed on your system.");
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
var xmlReq = createXMLHTTP();
// 发送ajax处理请求(这里简单验证用户名和密码的有效性,默认正确的输入:用户名和密码都是test)
function validatePwd(oTxt) {
var url = "/AjaxOperations.aspx?action=jsonOp";
// JSON就只是文本,由于不需要特殊编码而且每个服务器端脚本都能处理文本数据,
//所以可以轻松利用JSON并将其应用到服务器。
var str = '{ "userName":"' + $("txtUserName").value + '", "userPwd": "' + $("txtPwd").value + '"}';
var jsonStr = str.parseJSON().toJSONString(); // you're sending it JSON
xmlReq.open("post", url, true);
xmlReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlReq.onreadystatechange = callBack;
xmlReq.send("sendStr=" + jsonStr); // 发送JSON(在服务器上解释JSON)
}
function callBack() {
if (xmlReq.readyState == 4) {
if (xmlReq.status == 200) {
var jsonStr = xmlReq.responseText.parseJSON().toJSONString(); //转化为json数据
alert(jsonStr);
}
else if (xmlReq.status == 404) {
alert("Requested URL is not found.");
} else if (xmlReq.status == 403) {
alert("Access denied.");
} else
alert("status is " + xmlReq.status);
}
}
附加文件,AjaxOperations.aspx的html页面没有改变,AjaxOperations.aspx.cs代码稍作调整如下:
// 此函数等价于document.getElementById /document.all
function $(s) { if (document.getElementById) {
return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }
// 创建 XMLHttpRequest对象,以发送ajax请求
function createXMLHTTP() {
var xmlHttp = false;
var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
"Microsoft.XMLHTTP"];
for (var i = 0; i < arrSignatures.length; i++) {
try {
xmlHttp = new ActiveXObject(arrSignatures[i]);
return xmlHttp;
}
catch (oError) {
xmlHttp = false; //ignore
}
}
// throw new Error("MSXML is not installed on your system.");
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
var xmlReq = createXMLHTTP();
// 发送ajax处理请求(这里简单验证用户名和密码的有效性,默认正确的输入:用户名和密码都是test)
function validatePwd(oTxt) {
var url = "/AjaxOperations.aspx?action=jsonOp";
// JSON就只是文本,由于不需要特殊编码而且每个服务器端脚本都能处理文本数据,
//所以可以轻松利用JSON并将其应用到服务器。
var str = '{ "userName":"' + $("txtUserName").value + '", "userPwd": "' + $("txtPwd").value + '"}';
var jsonStr = str.parseJSON().toJSONString(); // you're sending it JSON
xmlReq.open("post", url, true);
xmlReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlReq.onreadystatechange = callBack;
xmlReq.send("sendStr=" + jsonStr); // 发送JSON(在服务器上解释JSON)
}
function callBack() {
if (xmlReq.readyState == 4) {
if (xmlReq.status == 200) {
var jsonStr = xmlReq.responseText.parseJSON().toJSONString(); //转化为json数据
alert(jsonStr);
}
else if (xmlReq.status == 404) {
alert("Requested URL is not found.");
} else if (xmlReq.status == 403) {
alert("Access denied.");
} else
alert("status is " + xmlReq.status);
}
}
Code
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebTest2008
{
public partial class AjaxOperations : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request["action"]) && Request["action"] == "jsonOp") // 处理JSON
{
string responseJsonTxt = "";
string tempStr = Request["sendStr"].Trim(new char[] { '{', '}' });
// 在服务器上解释JSON需要引用一个能够转化JSON的组件:Json.Net,这里简单测试,略过Json.Net
if (tempStr.Split(new char[] { ',' })[0].Split(new char[] { ':' })[1] == "\"test\"" && tempStr.Split(new char[] { ',' })[1].Split(new char[] { ':' })[1] == "\"test\"")
{
responseJsonTxt = "{\"msg\":\"验证通过!\"}"; // 测试用
}
else responseJsonTxt = "{\"msg\":\"验证失败!\"}";
Response.Write(responseJsonTxt);
Response.End();
}
}
jsTest.html引入json.js文件(必须下载json.js文件,否则js报错),如下:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebTest2008
{
public partial class AjaxOperations : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request["action"]) && Request["action"] == "jsonOp") // 处理JSON
{
string responseJsonTxt = "";
string tempStr = Request["sendStr"].Trim(new char[] { '{', '}' });
// 在服务器上解释JSON需要引用一个能够转化JSON的组件:Json.Net,这里简单测试,略过Json.Net
if (tempStr.Split(new char[] { ',' })[0].Split(new char[] { ':' })[1] == "\"test\"" && tempStr.Split(new char[] { ',' })[1].Split(new char[] { ':' })[1] == "\"test\"")
{
responseJsonTxt = "{\"msg\":\"验证通过!\"}"; // 测试用
}
else responseJsonTxt = "{\"msg\":\"验证失败!\"}";
Response.Write(responseJsonTxt);
Response.End();
}
}
Code
<html>
<head>
<title>js test</title>
<script src="js/json.js" type="text/javascript"></script>
<script src="js/testJs.js" type="text/javascript"></script>
</head>
<body>
<form id="form1">
<div>
用户名:<input id="txtUserName" name="txtUserName" type="text" />
密码:<input id="txtPwd" name="txtPwd" type="password" onblur="validatePwd(this)" /></div>
</form>
</body>
</html>
<html>
<head>
<title>js test</title>
<script src="js/json.js" type="text/javascript"></script>
<script src="js/testJs.js" type="text/javascript"></script>
</head>
<body>
<form id="form1">
<div>
用户名:<input id="txtUserName" name="txtUserName" type="text" />
密码:<input id="txtPwd" name="txtPwd" type="password" onblur="validatePwd(this)" /></div>
</form>
</body>
</html>