日期:2014-05-16  浏览次数:20803 次

.NET网站中利用jQuery Ajax获取后台数据
一般处理程序
using System.Web.Script.Serialization;
using System.Collections.Generic;
JavaScriptSerializer jss = new JavaScriptSerializer();
Person[] person = {
   new Person(){ Name="Tom",Sex="男",Age=30 },
   new  Person(){ Name="Json",Sex="女",Age=24 }
};
string JSON = jss.Serialize(person);
context.Response.Write(JSON);
...
public class Person
{
   new Person(){ Name="Tom",Sex="男",Age=30 },
   new  Person(){ Name="Json",Sex="女",Age=24 },
   new  Person(){ Name="Json1",Sex="女",Age=24 },
   new  Person(){ Name="Json2",Sex="女",Age=24 },
   new  Person(){ Name="Json3",Sex="女",Age=24 },
   new  Person(){ Name="Json4",Sex="女",Age=24 }
}
List<Person> list = new List<Person>();
foreach (var per in person)
{
    list.Add(new Person() { Name=per.Name,Sex=per.Sex,Age=per.Age });
}
string JSON = jss.Serialize(list);
context.Response.Write(JSON);
...
public class Person
{
    public string Name { get; set; }
    public string Sex { get; set; }
    public int Age { get; set; }
}
前台:
<script type="text/javascript">
$(function(){
    $.post("Servers/Postdata.ashx",function(data,status){
        var person = $.parseJSON(data);
        alert(person[1].Name);
    });
})
结果:Json2