###准备步骤
####引用Newtonsoft.dll文件
将Newtonsoft放到项目所在文件夹中,在项目的解决方案中单机右键—添加—引用—浏览—选中Newtonsoft.dll。
####两个实例
一、前端发送post请求
前端代码
```
var userInfo={k:{v:"秦川"},arr:[1,2,3]};//这是一个复杂json
$.ajax({
type:"post",
url:"你后端的ashx文件",
data:{
name:"qinchuan",//向后端发送普通的key、value
age:21,//向后端发送普通的key、value
userObj:JSON.stringify(userInfo)//向后端发送对象、数组以及复杂的json(必须先通过JSON.stringify进行序列化)
},
dataType:"json",
success:function(res){
console.log(res);//输出后端返回的数据
}
});
```
后端代码
```
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;//必须引入这两个才能使用json;
//在public void ProcessRequest(HttpContext context)方法中:
context.Response.ContentType = "application/json";//指定返回给前端的类型是json
string userName = context.Request.Form["name"];//接收前端发送的post数据
string age=context.Request.Form["age"];
//根据userName和age去查询数据库,返回dataset类型,存放到ds中
DataSet ds=你的数据库返回的dataset;
//假设数据库返回的Dataset中有phone、address字段
DataTable dt=ds.Tables[0];
DataRow dr=dt.Rows;
JArray arr=new JArray();//创建一个json数组
for(int i=0;i
JObject obj=new JObject();//创建一个json对象
obj.Add("phone",dr[i]["phone"]);//如果这里报错就把dt[i]["phone"]转换成string类型
obj.Add("phone",dr[i]["address"]);
arr.Add(obj);//把json对象添加到惊悚数组中
}
context.Response.Write(arr);//把json数组返回给前端
```
```
前端最终接收到的数据为:
[
{"phone":123,"address":456},
{"phone":353,"address":245},
{"phone":313,"address":321}
] //包含有若干对象的数组
```
二、前端发送get请求
前端代码
```
和post请求大同小异,把$.ajax里面的type改成"get"即可
```
后端代码
```
string userName = context.Request.Params["name"];//接收前端发送的get数据
string age=context.Request.Params["age"];
//之后的代码和post相同
```