jquery ajax json案例
http://wenku.baidu.com/view/e3d4d21fc5da50e2524d7f81.html
JSON数据读写
教学目的:
理解JSON数据读写的类型
掌握JSON数据读写各种方法
教学内容:
一、JSON数据读写的类型
1. 客户端读取JSON数据的方法
2. 读取服务器端一个对象数据
3. 读取服务器端一组对象数据
4. 发送并接受服务器端数据
二、JSON数据读写方法
1.客户端读取JSON数据的方法:将JSON数据文本变成JSON数据:
eval(“var jsondata=”+jsondatatext);
用jsondata访问其中的数据,这种读写方法意义不大,大多数情况下,它应同服务器端交互。
function readlocaldata()
{
var val1="'软件专业'";
var val2="true";
var val3="23";
var arr="[12,34,56]";
var obj="{name:'张三',age:23}";
eval("var json="+val1+";");alert("我学的是"+json);
eval("var json="+val2+";");alert(!json);
eval("var json="+val3+";");alert(2*json);
eval("var json="+arr+";");alert(json[1]);
eval("var json="+obj+";");alert(json.name);
}
2.服务器与客户端的JSON数据的交换。
网络数据交换格式选择JSON数据格式。
为将服务器端的JSON数据送到客户端,服务器端要进行序列化;为接受客户端的JSON文本格式数据服务器端要进行反序列化。服务器端序列化和反序列化操作需要JSON类库。搜索、下载、解压文件,得到Newtonsoft.Json.Net20.dll,并在项目中添加引用..。
一般步骤如下:
1. 导入JSON类库
2. 定义服务器端的实体类。
3. 定义服务器端的一般处理程序。
4. 定义客户端的请求页面。
为调用服务器端序列化和反序列化方法,需要定义相关的实体类。
定义实体类Product.cs
public class Product
{
public string Name { get; set; }
public DateTime Expiry { get; set; }
public float Price { get; set; }
public string[] Sizes { get; set; }
}
定义实体类Person.cs
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
用一般处理程序ashx接受并响应客户端。
定义返回一个对象数据的服务器端处理程序GetProduct.ashx
<%@ WebHandler Language="C#" Class="GetProduct" %>
using System;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class GetProduct : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99F;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product);
context.Response.Write(output);
}
public bool IsReusable {
get {
return false;
}
}
}
定义返回一组对象数据的服务器端处理程序
GetPersons.ashx
<%@ WebHandler Language="C#" Class="GetPersons" %>
using System;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class GetPersons : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
Person[] persons = new Person[]{
new Person("aa",32),
new Person("bb",33),
new Person("cc",34),
new Person("dd",35)};
//序列化
string output = JsonConvert.SerializeObject(persons);
context.Response.Write(output);
}
}
发送客户端请求数据并接受服务器端响应数据GetClientJSON.ashx
<%@ WebHandler Language="C#" Class="GetClientJSON" %>
using System;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class GetClientJSON : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//string jsonText = "{name:'aa',age:23}";
string jsonText = context.Request["person"];
//反序列化
Person person = (Person)JsonConvert.DeserializeObject(jsonText, typeof(Person));
context.Response.Write(person.Name+"<br />"+person.Age);
}
}
定义客户端页面,用AJAX方式请求并更新页面
读取服务器端数据GetServerData.htm
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>读写服务器端数据</title>
<script type="text/javascript" src="jquery-1.4.js">
</script>
</head>
<body>
<input id="Button1" type="button" value="读取服务器端一个对象数据" onclick="readdata();" />
<input id="Button2" type="button" value="读取服务器端一组对象数据" onclick="readdataarray();" />
<input id="Button3" type="button" value="给服务器端发送数据" onclick="senddata();" />
<div id="product" ></div>
<div id="persons" ></div>
<div id="person" ></div>
</body>
</html>
<script type="text/javascript">
function readdata()
{
$.getJSON("getproduct.ashx", function(data){
$("div#product").append(data.Name+"<br />");
$("div#product").append(data.Expiry+"="+ChangeDateFormat(data.Expiry)+"<br />");
$("div#product").append(data.Price+"<br />");
for(i=0;i<data.Sizes.length;i++)
//或:for(i in data.Sizes)
$("div#product").append(data.Sizes[i]+" ");
$("div#product").append("<br />");
});
}
function readdataarray()
{
$.getJSON("getpersons.ashx", function(data){
for(i in data)
{
$("div#persons").append(data[i].Name+" "+data[i].Age+"<br />");
}
});
$.getJSON("getpersons.ashx", function(data){
var s=
"<table style='background:#eee;' width=200><tr><td>Name</td><td>Age</td></tr>";
for(i in data)
{
s+="<tr><td>"+data[i].Name+"</td><td>"+data[i].Age+"</td></tr>";
}
s+="</table>"
$("div#persons").append(s);
$("table tr:odd").css('background','#fee');
$("table tr:even").css('background','#efe');
$("table tr td").bind('mouseenter mouseleave',function()
{
$(this).parent().children().toggleClass('mouse');
}
);
}
function senddata()
{
$.post("GetClientJSON.ashx",{person:"{ age:23,name:'aa'}"},function(data)
{
$("div#person").append(data);
});
}
function ChangeDateFormat(cellval)//日期格式的转换
{
var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
return date.getFullYear() + "-" + month + "-" + currentDate;
}
</script>
作业:
举例说明JSON数据客户端解析方法
举例说明用JSON数据格式获取登录信息的过程。
从数据集中读取JSON数据
<%@ WebHandler Language="C#" Class="GetData" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class GetData : IHttpHandler
{
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
SqlConnection cnn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;User ID=sa;Password=123");
SqlDataAdapter adp = new SqlDataAdapter("SELECT CategoryID,CategoryName FROM Categories", cnn);
DataSet ds = new DataSet();
adp.Fill(ds);
DataRowCollection rows = ds.Tables[0].Rows;
//直接序列化ds.Tables[0].Rows会产生许多的冗余信息。
Category[] Categories=new Category[rows.Count];
for (int i = 0; i < rows.Count; i++)
Categories[i] = new Category((int)rows[i]["CategoryID"], rows[i]["CategoryName"].ToString());
context.Response.Write(JsonConvert.SerializeObject(Categories));
}
public bool IsReusable {
get {
return false;
}
}
//定义内部实体类
public class Category
{
int categoryID;
public int CategoryID
{
get { return categoryID; }
set { categoryID = value; }
}
string categoryName;
public string CategoryName
{
get { return categoryName; }
set { categoryName = value; }
}
public Category(int categoryID,string categoryName)
{
this.categoryID = categoryID;
this.categoryName = categoryName;
}
}
}
显示数据如下:
[
{"CategoryID":1,"CategoryName":"Beverages"},
{"CategoryID":2,"CategoryName":"Condiments"},
{"CategoryID":3,"CategoryName":"Confections"},
{"CategoryID":4,"CategoryName":"Dairy Products"},
{"CategoryID":5,"CategoryName":"Grains/Cereals"},
{"CategoryID":6,"CategoryName":"Meat/Poultry"},
{"CategoryID":7,"CategoryName":"Produce"},
{"CategoryID":8,"CategoryName":"Seafood"}
]
posted on 2013-09-25 11:19 master2012 阅读(141) 评论(0) 收藏 举报
浙公网安备 33010602011771号