在返回Response.Write()后应该调用Response.End()才能将数据写入到调用的页面,才能被JQuery的回调函数获取到返回的JSON数据
HTML页面,使用$.post()方法向ASPX提交请求,获取JSON数据
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function ()
{
$("#btnGetJson").click(function ()
{
$.post("JSONGenerator.aspx", "a=a", function (data)
{
alert(data.returnCode);
}, "json");
});
});
</script>
</head>
<body>
<input type="button" id="btnGetJson" value="确定"/>
</body>
</html>
JSONGenerator.aspx页面,写入JSON数据后要调用Response.End()方法将数据发回到调用处
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyWeb
{
public partial class JSONGenerator : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("{\"returnCode\":"+2+"}");
Response.End();
}
}
}