首先创建一个一般处理程序“ResponseJson.ashx”,手动拼接字符串返回Json格式:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
List<cityInfo> cityInfos = new List<cityInfo>()
{
new cityInfo(){cityID=1,cityName="北京"},
new cityInfo(){cityID=2,cityName="上海"},
new cityInfo(){cityID=3,cityName="南京"},
new cityInfo(){cityID=4,cityName="深圳"},
new cityInfo(){cityID=5,cityName="广州"}
};
// 自己拼接Json 这种方式较灵活
StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (cityInfo cityInfo in cityInfos)
{
sb.Append("{");
sb.AppendFormat("\"cityID\":{0},\"cityName\":\"{1}\"",cityInfo.cityID,cityInfo.cityName);
sb.Append("}");
sb.Append(",");
}
string str = sb.ToString().TrimEnd(',');
str += "]";
context.Response.Write(str);
// 或者将对象序列化成Json格式 和拼接相比这种方式较为死板
//System.Web.Script.Serialization.JavaScriptSerializer JSSerializer = new JavaScriptSerializer();
//string Json = JSSerializer.Serialize(cityInfos);
//context.Response.Write(Json);
}
public bool IsReusable
{
get
{
return false;
}
}
}
public class cityInfo
{
public string cityName
{
get;
set;
}
public int cityID
{
get;
set;
}
}
然后创建一个html页“getJson.htm” 并且引入Jquery.添加一个button
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
</script>
</head>
<body>
<input type="button" id="btnGetJson" value="获取Json" />
</body>
</html>
javascript 获取Json:
<script type="text/javascript">
$(function () {
$("#btnGetJson").click(function () {
var xhr;
// 创建异步请求的对象
if (XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
// xhr = new ActiveXObject(XMLHttpRequest);
// 或者用
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// 打开
xhr.open("get","ResponseJson.ashx",true);
// 发送
xhr.send();
// 回调
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var jsonData = $.parseJSON(xhr.responseText);
alert(jsonData[1].cityName);
// alert(xhr.responseText);
} else {
alert("服务器错误" + xhr.status);
}
}
}
})
});
</script>
运行后弹出的结果:“上海”
原文链接:https://www.f2er.com/ajax/166152.html