GET方式获得JSON数据
$(function () {
$("#btnGetJson").click(function () {
var xhr;
if (XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("Get", "ResponseJson.ashx", true);
xhr.send();
xhr.onreadystatechange = function () {
//str→json
if (xhr.readyState == 4) {
var jsonData = $.parseJSON(xhr.responseText);
alert(jsonData[0].CityName);
}
};
});
});
html代码:
<input type="button" id="btnGetJson" value="获取json"/>
后台代码:
//第一种:拼接字符串,这种方式比较灵活
System.Collections.Generic.List<CityInfo> cities = 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 = "烟台"}
};
//[{CityId:1,CityName:"潍坊"},{},{}]
//第一种:拼接字符串,这种方式比较灵活
System.Text.StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (var cityInfo in cities)
{
sb.Append("{");
sb.AppendFormat("\"CityId\":\"{0}\",\"CityName\":\"{1}\"", cityInfo.CityId, cityInfo.CityName);
sb.Append("},");
}
string str = sb.ToString().TrimEnd(',');
str += "]";
context.Response.Write(str);
//第二种序列化的方式
//如果对象之间有循环依赖,则会出现问题
//将对象序列化成json格式:
System.Web.Script.Serialization.JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(cities);
context.Response.Write(json);
前台4种AJAX请求的方式:
$(function () {
$("#btnGetJson").click(function () {
$.getJSON("ResponseJson.ashx", "a=3&b=4", function (data) {
alert(data[1].CityName);
});
});
$("#btnJQGet").click(function () {
$.get("ResponseJson.ashx", "dd=33", function (data) {
alert(data);
});
});
//直接post比较方便
$("#btnJQPost").click(function () {
$.post("ResponseJson.ashx", { d: 33, demo: 'shit' }, function (data) {
alert(data[0].CityName);
}, "json");
});
//综合性的
$("#btnAjax").click(function () {
$.ajax({
url: "ResponseJson.ashx",
data: "a=3&b=4",
type: "Post",
success: function (data) {
alert(data);
$("#divDemo").text(data);
},
error: function () {
alert("错误!");
}
});
});
$("#btnLaod").click(function () {
//先定位到 dom元素上,再调用load
$("#divDemo").load("ResponseJson.ashx", { id: 333 }, function (data) {
alert(data);
});
});
});
</script>
</head>
<body>
<input type="button" value="JQ GetJson" id="btnGetJson"/>
<input type="button" value="JQ Get" id="btnJQGet"/>
<input type="button" value="JQ Post" id="btnJQPost"/>
<input type="button" value="JQ ajax" id="btnAjax"/>
<input type="button" value="JQ load" id="btnLaod"/>
<div id="divDemo">
</div>
<table id="demo">
其中<input type="button" value="JQ ajax" id="btnAjax"/> 是先ALERT,再显示数据
<input type="button" value="JQ load" id="btnLaod"/>是先显示数据,再ALERT