html页面中:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="../Js/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(function() {
//声明从服务器返回的数据类型是JSON对象类型。
$("#btnData").click(function() {
$.post("GetJson.ashx", {}, function(data) {
alert("用户名是:" + data.Name);
}, "json"); //声明数据类型是JSON对象
});
//第二种方式
$("#btnData1").click(function() {
$.post("GetJson.ashx", {}, function(data) {
var serverData = $.parseJSON(data); //将字符串转成JSON对象类型
alert("用户名是:" + serverData.Name);
});
});
//第三种方式
$("#btnData2").click(function() {
$.getJSON("GetJson.ashx", {}, function(data) { //get请求方式
alert("用户名是:" + data.Name);
});
});
//第四种方式
$("#btnAjax").click(function() {
$.ajax({
type: "POST",
url: "GetJson.ashx",
data: "name=John&location=Boston",
dataType: "json", //返回数据的数据类型是JSON对象,默认是"text"表示字符串。
success: function(data) {
alert("用户名是:" + data.Name);
}
});
});
});
</script>
</head>
<body>
<input type="button" value="获取数据" id="btnData" />
<input type="button" value="获取数据1" id="btnData1" />
<input type="button" value="获取数据2" id="btnData2" />
<input type="button" value="获取数据2" id="btnAjax" />
</body>
</html>
GetJson.ashx.csusing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace XXX.WebApp
{
/// <summary>
/// GetJson 的摘要说明
/// </summary>
public class GetJson : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("{\"Name\":\"zhangsan\",\"Age\":\"12\"}"); //返回JSON对象字符串
}
public bool IsReusable
{
get
{
return false;
}
}
}
}