2011-08-19 30 views
1

我有一个简单的C#类,名为Employee,它有两个属性Name,Age。 我需要创建一个员工列表并序列化成JSON并在jQuery中访问。使用jQuery读取从ASP.NET返回的JSON

我已成功转换为JSON。 但我坚持通过jquery查阅。

public class Employee 
{ 
    public string Name { get; set; }  
    public int Age { get; set; } 
} 

protected void Page_Load(object sender, EventArgs e) 
{ 
    IList<Employee> employeeList = new List<Employee>() {   
    new Employee() { Name = "XXX", Age=20}, 
    new Employee() { Name = "YYY", Age=24} 
    new Employee() { Name = "kamal", Age=24} 
}; 

System.Web.Script.Serialization.JavaScriptSerializer objectSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();  
string jsonObj = objectSerializer.Serialize(employeeList); 
Response.Write(jsonObj); 
} 

任何想法.. ??

提前致谢。

+1

你有什么用jQuery这么远?你可能想看看'jQuery.getJSON'。 – pimvdb

回答

1

您应该将json对象写入脚本标记并将其分配给某个变量以便使用它。试试这个

Response.Write("<script type='text\javascript\> var employeeObj = "+jsonObj+"</script>"); 

使用jQuery中

//Looping through employeeObj using each method. Inside each this points to each item in the array and you can use this.Name and this.Age to retreive the values. 
$.each(employeeObj, function(){ 
    alert("Name: " + this.Name + " Age: "+ this.Age); 
}); 
+0

@dhinesh - 这对你有帮助吗? – ShankarSangoli

+0

我试过这个,但仍然没有得到答案。 – Dinesh

+0

你在哪里试图使用这个对象? – ShankarSangoli

0
$.ajax(
    {url: "your url to get data", 
    type="get", 
    dataType: "json", 
    success: function(data) { //data is your json 
    } 
); 

就是Ajax调用,但如果你要访问它的变量,你应该写它通过C#这样

String.Format("<script language="javascript"> 
    var myJson = {0}; 
</script>", jsonObj) 

然后你可以从javascript访问它,如

myJson; 
0

Json.js

使用JavaScript文件,并使用

var jsonObject = JSON.parse(string);