Jquery由于提供的$.ajax强大方法,使得其调用webservice实现异步变得简单起来,可以在页面上传递Json字符串到Webservice中,Webservice方法进行业务处理后,返回Json对象给页面,让页面去展现。
这一切都非常的简单,今天要学习的并非这些。我们在实际处理业务过程中,会发现往往页面要传递给webservice 的并非一个或多个字符串,有时候需要传递的是一个组合数据,如这样的一组数据:
{'Employee': [{'name':'John','sex':'man','age':'25'},{'name':'Tom','sex':'man','age':'21'}]}
客户端将这样的Json字符串作为$.ajax方法的data参数是没有问题的,然而,服务端的webservice该如何去写接收参数却成为了一个问题。在百度、谷歌了一番后,只发现提问的却没有回答的。索性还是自己去研究吧,发现其实Employee对象首先是一个数组,其次数组的每一项都是一个Dictionary<string,string>字典类型。于是我尝试在服务端使用Dictionary<string,string>[] Employee来接收客户端传递的参数,一切如我所料,成功!
客户端代码如下:
代码 //JQuery 调用webService导入数据
function LoadData() {
var studentData = CollectionData();
$.ajax({
url: "ImportDataService.asmx/ImportStu",
type: "post",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: "{'students':[{'name':'KoBe ','sex':'boy','age':'20'},{'name':'Mary','sex':'girl','age':'19'}]}",
success: function(result) {
alert(result.d);
},
error: function(e) {
alert(e.responseText);
}
});
}
服务端代码如下:
代码 /// <summary>
///
/// </summary>
/// <param name="students"></param>
/// <returns></returns>
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string ImportStu(Dictionary<string,string> []students)
{
if (students.Length == )
{
return "没有任何数据!";
}
else
{
try
{
foreach (Dictionary<string, string> stu in students)
{
//构造一个新的Student对象。
Student student = new Student(); //为新构造的Student对象属性赋值。
foreach (string key in stu.Keys)
{
switch (key)
{
case "name":
student.Name = stu[key];
break;
case "sex":
student.Sex = stu[key];
break;
case "age":
int age;
if (Int32.TryParse(stu[key], out age))
{
student.Age = age;
}
else
{
student.Age = ;
}
break;
default:
break;
}
}
}
return "导入学生成功!";
}
catch
{
throw new Exception("导入学生失败!");
}
}
}
需要注意的是,服务端参数名需要和客户端Json数组的key值相同,如上代码中,参数名都为students。
以上是转自:http://www.cnblogs.com/RascallySnake/archive/2010/04/08/1707521.html
服务端代码如下:
using System.Web.Script.Services;
using System.Web.Services;
using WebWeatherWarning.Action; namespace WebWeatherWarning
{
/// <summary>
/// WeatherService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[ScriptService]
public class WeatherService : WebService
{ [WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string GetWeather()
{
const string sql = "SELECT * FROM DUAL";
var result=WeatherTask.GetInstance().GetWeather(sql);
return result != null ? ParseTags(result) : null;
}
public static string ParseTags(string htmlStr)
{
return System.Text.RegularExpressions.Regex.Replace(htmlStr, "<[^>]*>", "");
}
}
客户端代码如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="Lib/jquery-1.8.2.min.js"></script>
<script>
$(function() {
$("#btnQuery").click(function() {
$.ajax({
type: "GET", //访问WebService使用Post方式请求
contentType: "application/json;charset=utf-8", //WebService 会返回Json类型
url: "/WeatherService.asmx/GetWeather", //调用WebService
data: "{}", //Email参数
dataType: 'json',
beforeSend: function (x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); },
error: function (x, e) { },
success: function (response) { //回调函数,result,返回值
debugger; var json = eval('(' + response.d + ')');
if (json && json.length > ) {
$("#content").html(json[].PCONTENT);
} else {
alert("没有数据!!!");
}
}
}); }); }) </script>
</head> <body>
<input id="btnQuery" type="button" value="button"/>
<div>
<p id="content"></p>
</div>
</body>
</html>
配置文件代码如下:
web.config里需要配置2个地方
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpHandlers>
在<system.web></system.web>之间加入
<webServices>
<protocols>
<add name="HttpPost" />
<add name="HttpGet" />
</protocols>
</webServices>
<system.web>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpHandlers>
<httpRuntime/>
<webServices>
<protocols>
<add name="HttpPost"/>
<add name="HttpGet"/>
</protocols>
</webServices>
<pages controlRenderingCompatibilityVersion="4.0"/>
<compilation debug="true"/>
</system.web>