使用jQuery的$.getJson方法可以异步的获取服务器端返回的json字符串。
$.getJson方法语法
|
$.getJson(url,parameters,callback) |
|
|
参数 |
|
|
url |
(字符串)将要通过GET方法进行交互的服务器端资源的url。 |
|
parameters |
(对象)一个对象,其属性作为“键/值”用于构造查询字符串并追加到url;或者一个预格式化和uri编码的查询字符串。 |
|
callback |
(函数)回调函数,在请求完成时被调用。把响应体解析为json字符串,这个字符串的值作为第一个参数传递到这个回调函数,响应状态作为第二个参数传递到该函数。 |
|
返回值 |
XHR实例 |
下面看个例子
客户端代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function () {
$('#clk').click(function () {
var num = $(this).val();
$.getJSON('Server.aspx', callback)
})
function callback(json, status) {
$.each(json, function (i) {
$('#show').append('name:' + json[i]['Name'] + 'age:' + json[i]['Age'] + '<br/>');
})
}
})
</script>
</head>
<body>
<input id="clk" type="button" value="button" />
<div id="show">
</div>
</body>
</html>
服务端主要代码:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;//适用于.NetFramework 3.5
public partial class Server : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//List<Person> per = new List<Person>();
//per.Add(new Person("张三", 18));
//per.Add(new Person("李四", 19));
//JavaScriptSerializer jsonHelper = new JavaScriptSerializer();
//string json = jsonHelper.Serialize(per);
//Response.Write(json);
Response.Write(GetJSONData());
}
}
protected string GetJSONData()
{
string str = string.Empty;
//特别要注意json的返回格式,如果格式不正确将不能正常调用客户端的回调函数
str = "[{\"Name\":\"张三\",\"Age\":\"14\"}," +
"{\"Name\":\"李四\",\"Age\":\"17\"}," +
"{\"Name\":\"王五\",\"Age\":\"19\"}]";
return str;
}
public class Person
{
private string name;
private int age;
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
}
}
运行程序,结果如图:
如果你不熟悉json格式,也不要紧。可以使用System.Web.Script.Serialization(framework 3.5)命名空间下为格式化为json的帮助类。我们可以把服务器端Page_Load事件中注释的代码变为可用。把Response.Write(GetJSONData())这句注释掉。再运行程序,结果没有问题,如下图。它把类直接格式化为json字符串,省去了很多时间。

