前端脚本
1 $("#sure").click(function () { 2 var tbody = $("#putsigal tbody"); 3 var trs = tbody.find("tr"); 4 var houses = "{\"houses\":["; 5 trs.each(function (i) { 6 var housename = $(this).find(‘input[name="housename"]‘).val(); 7 var houseaddress = $(this).find(‘input[name="houseaddress"]‘).val(); 8 var area = $(this).find(‘input[name="area"]‘).val(); 9 alert(housename + "-" + houseaddress + "-" + area); 10 if (!housename || !houseaddress || !area) { 11 alert("第" + (i + 1) + "行的仓库信息不完整"); 12 return false; 13 } else { 14 var num = /^[1-9][0-9]+(.[0-9]{1,2}){0,1}$/; 15 if (!num.test(area)) { 16 alert("第" + (i + 1) + "行的仓库面积输入不合法"); 17 return false; 18 } 19 20 houses += "{\"housename\":" + "\"" + housename + "\",\"houseaddress\":\"" + houseaddress + "\",\"area\":\"" + area + "\"},"; 21 } 22 23 }) 24 var value = houses.substring(0, houses.length - 1); 25 value += "]}"; 26 27 $.ajax({ 28 type: "post", 29 url: "/Service.asmx/AddHouse", 30 dataType: "json", 31 //contentType: "application/json; charset=utf-8", 32 data: { house: value }, 33 success: function (data) { 34 // alert(data); 35 if (data.result == "1") { 36 alert(data.message); 37 window.location.href = "WareHouse.aspx"; 38 } else { alert(data.message); } 39 }, 40 error: function(x, e) { 41 alert(x.responseText); 42 }, 43 44 }); 45 });
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(); }
1 [WebMethod] 2 public string AddHouse(string house) 3 { 4 HouseBll hb = new HouseBll(); 5 JavaScriptSerializer js = new JavaScriptSerializer(); 6 Context.Response.Clear(); 7 Context.Response.ContentType = "aplication/json"; 8 string jsontext = house; 9 List<Warehouse> hs = new List<Warehouse>(); 10 Data result = new Data(); 11 JsonToobj json = new JsonToobj(); 12 hs = json.JsonToHouses(jsontext); 13 foreach (Warehouse h in hs) 14 { 15 try { hb.AddHouse(h); result.result = "1"; result.message = "成功插入"; } 16 catch { result.result = "0"; result.message = "发生异常"; } 17 } 18 19 return js.Serialize(result); 20 21 }
可以看到这个方法在写法上只有标红部分不同以及返回类型不同,其余均相同。第一个写法返回纯粹的json字符串,前端可以直接识别(本例中的前端脚本采用的第一种写法),而第二种写法则返回的是xml格式。在其格式下将json字符串包含在节点中。这种方式显然不是最方便的。原因就在于webservice 直接返回的是xml格式,而采用response.write的方法则是直接将结果写入返回流中,因此没有额外的格式限制。
时间: 2024-10-14 23:52:00