使用jQuery读取从ASP.NET返回的JSON

时间:2011-08-19 12:04:36

标签: jquery asp.net json

我有一个名为Employee的简单C#类,它有两个属性,Name,Age。 我需要创建一个员工列表并序列化为JSON并在jquery中访问。

我已成功转换为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);
}

任何想法.. ??

提前感谢。

3 个答案:

答案 0 :(得分: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);
});

答案 1 :(得分: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;

答案 2 :(得分:0)

Json.js

使用javascript文件并使用

var jsonObject = JSON.parse(string);