亲测 asp.net 调用 webservice返回json

前端脚本

 $("#sure").click(function () {
var tbody = $("#putsigal tbody");
var trs = tbody.find("tr");
var houses = "{\"houses\":[";
trs.each(function (i) {
var housename = $(this).find('input[name="housename"]').val();
var houseaddress = $(this).find('input[name="houseaddress"]').val();
var area = $(this).find('input[name="area"]').val();
alert(housename + "-" + houseaddress + "-" + area);
if (!housename || !houseaddress || !area) {
alert("第" + (i + ) + "行的仓库信息不完整");
return false;
} else {
var num = /^[-][-]+(.[-]{,}){,}$/;
if (!num.test(area)) {
alert("第" + (i + ) + "行的仓库面积输入不合法");
return false;
} houses += "{\"housename\":" + "\"" + housename + "\",\"houseaddress\":\"" + houseaddress + "\",\"area\":\"" + area + "\"},";
} })
var value = houses.substring(, houses.length - );
value += "]}"; $.ajax({
type: "post",
url: "/Service.asmx/AddHouse",
dataType: "json",
//contentType: "application/json; charset=utf-8",
data: { house: value },
success: function (data) {
// alert(data);
if (data.result == "") {
alert(data.message);
window.location.href = "WareHouse.aspx";
} else { alert(data.message); }
},
error: function(x, e) {
alert(x.responseText);
}, });
});

webservice 代码

[WebMethod]
public void AddHouse(string house)
{
HouseBll hb = new HouseBll();
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "aplication/json";
string jsontext = house;
List<Warehouse> hs = new List<Warehouse>();
Data result = new Data();
JsonToobj json = new JsonToobj();
hs = json.JsonToHouses(jsontext);
foreach (Warehouse h in hs)
{
try { hb.AddHouse(h); result.result = "1"; result.message = "成功插入"; }
catch { result.result = "0"; result.message = "发生异常"; }
} Context.Response.Write(js.Serialize(result));
Context.Response.End();
}
 [WebMethod]
public string AddHouse(string house)
{
HouseBll hb = new HouseBll();
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "aplication/json";
string jsontext = house;
List<Warehouse> hs = new List<Warehouse>();
Data result = new Data();
JsonToobj json = new JsonToobj();
hs = json.JsonToHouses(jsontext);
foreach (Warehouse h in hs)
{
try { hb.AddHouse(h); result.result = ""; result.message = "成功插入"; }
catch { result.result = ""; result.message = "发生异常"; }
} return js.Serialize(result); }

可以看到这个方法在写法上只有标红部分不同以及返回类型不同,其余均相同。第一个写法返回纯粹的json字符串,前端可以直接识别(本例中的前端脚本采用的第一种写法),而第二种写法则返回的是xml格式。在其格式下将json字符串包含在节点中。这种方式显然不是最方便的。原因就在于webservice 直接返回的是xml格式,而采用response.write的方法则是直接将结果写入返回流中,因此没有额外的格式限制。

上一篇:【转】Gabor 入门


下一篇:解决mybatis foreach 错误: Parameter '__frch_item_0' not found