WebService Ajax调用
1.Html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="../js/jquery-1.9.1.js" type="text/javascript"></script> <script type="text/javascript"> // 无参 function BindCallHello() { $("#btnCallHello").click(function () { $.ajax({ type: "post", //访问WebService使用Post方式请求 url: "http://localhost:5606/Handler/UserService.asmx/HelloWebService", //调用Url(WebService的地址和方法名称组合---WsURL/方法名) data: {}, //这里是要传递的参数,为Json格式{paraName:paraValue} contentType: "Application/Json", // 发送信息至服务器时内容编码类型 beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "Application/Json"); // 接受的数据类型。(貌似不起作用,因为WebService的请求/返回 类型是相同的,由于请求的是Json,所以,返回的默认是Json) }, success: function (data) { var jsonValue = data; alert(jsonValue.d); // 输出Json }, complete: function (XMLHttpRequest, textStatus) { var returnText = XMLHttpRequest.responseText; $("#backData").html(returnText); // 输出服务器端返回数据 } }); }); } // 传递单个参数 function BindCallBody() { $("#btnCallBody").click(function () { var name = $("#txtName").val(); $.ajax({ type: "post", //访问WebService使用Post方式请求 url: "http://localhost:5606/Handler/UserService.asmx/HelloSomeBody", //调用Url(WebService的地址和方法名称组合---WsURL/方法名) data: "{name:'" + name + "'}", //这里是要传递的参数,为Json格式{paraName:paraValue} contentType: "Application/Json", // 发送信息至服务器时内容编码类型 beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "Application/Json"); // 接受的数据类型。(貌似不起作用,因为WebService的请求/返回 类型是相同的,由于请求的是Json,所以,返回的默认是Json) }, success: function (data) { var jsonValue = data; alert(jsonValue.d); // 输出Json }, complete: function (XMLHttpRequest, textStatus) { var returnText = XMLHttpRequest.responseText; $("#backData").html(returnText); // 输出服务器端返回数据 } }); }); } //传递多个参数,返回类对象 function BindGetSingleStudent() { $("#btnSinStuInfo").click(function () { var stuSid = $("#txtStuSid").val(); var stuName = $("#txtStuName").val(); var stuSex = $("#txtStuSex").val(); var stuAge = $("#txtStuAge").val(); $.ajax({ type: "post", //访问WebService使用Post方式请求 url: "http://localhost:5606/Handler/UserService.asmx/SetStudentInfo", //调用Url(WebService的地址和方法名称组合---WsURL/方法名) data: "{name:'" + stuName + "',sex:'" + stuSex + "',age:'" + stuAge + "',sid:'" + stuSid + "'}", //这里是要传递的参数,为Json格式{paraName:paraValue} contentType: "Application/Json", // 发送信息至服务器时内容编码类型 beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "Application/Json"); // 接受的数据类型。(貌似不起作用,因为WebService的请求/返回 类型是相同的,由于请求的是Json,所以,返回的默认是Json) }, success: function (data) { var jsonValue = data; alert(jsonValue.d.Sid); // 输出Json $(data.d).each(function () { alert(this['Age'] + this["Name"]); }); }, complete: function (XMLHttpRequest, textStatus) { var returnText = XMLHttpRequest.responseText; $("#backData").html(returnText); // 输出服务器端返回数据 } }); }); } //返回List集合 function BindGetMulStudents() { $("#btnMulStuInfos").click(function () { $.ajax({ type: "post", //访问WebService使用Post方式请求 url: "http://localhost:5606/Handler/UserService.asmx/GetMulStudentInfos", //调用Url(WebService的地址和方法名称组合---WsURL/方法名) data: {}, //这里是要传递的参数,为Json格式{paraName:paraValue} contentType: "Application/Json", // 发送信息至服务器时内容编码类型 beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "Application/Json"); // 接受的数据类型。(貌似不起作用,因为WebService的请求/返回 类型是相同的,由于请求的是Json,所以,返回的默认是Json) }, success: function (data) { var jsonValue = data; alert(jsonValue.d[0].Sid); // 输出Json $(data.d).each(function () { alert(this['Age'] + this["Name"]); }); }, complete: function (XMLHttpRequest, textStatus) { var returnText = XMLHttpRequest.responseText; $("#backData").html(returnText); // 输出服务器端返回数据 } }); }); } //返回DataSet function BindGetDataSet() { $.ajax({ type: "POST", url: "http://localhost:5606/Handler/UserService.asmx/GetDataSet", data: "{}", dataType: 'xml', //返回的类型为XML ,和前面的Json,不一样了 success: function (result) { //演示一下捕获 try { $(result).find("Table1").each(function () { $('#backData').append($(this).find("ID").text() + " " + $(this).find("Value").text()); }); } catch (e) { alert(e); return; } }, error: function (result, status) { //如果没有上面的捕获出错会执行这里的回调函数 if (status == 'error') { alert(status); } } }); } //传递类对象、集合对象 function BindSetClassListInfos() { $.ajax({ type: "post", url: "http://localhost:5606/Handler/UserService.asmx/ComplexType", dataType: "json", contentType: "application/json", data: '{"hero": {"Name":"sxl","Age":25},"users":[{"Name":"zhang1","Age":22},{"Name":"wang1","Age":26},{"Name":"liu1","Age":25},{"Name":"luo1","Age":24}]}', success: function (data) { $("#web").text(data.d); } }); } </script> </head> <body> <input type="button" id="btn5" value="返回DataSet" onclick="BindGetDataSet();" /><hr /> <input id="btnWeb" type="button" value="传递类对象、集合对象" onclick="BindSetClassListInfos();" /><label id="web"></label> <div> <hr /> <input id="btnCallHello" type="button" value="调用无参方法,返回字符串" onclick="BindCallHello();" /> <hr /> 姓名:<input id="txtName" type="text" /><br /> <input id="btnCallBody" type="button" value="调用有参方法,返回字符串" onclick="BindCallBody();" /> <hr /> 学号:<input id="txtStuSid" type="text" /><br /> 姓名:<input id="txtStuName" type="text" /><br /> 性别:<input id="txtStuSex" type="text" /><br /> 年龄:<input id="txtStuAge" type="text" /><br /> <input id="btnSinStuInfo" type="button" value="调用SetStudentInfo" onclick="BindGetSingleStudent();" /><br /> <hr /> <input id="btnMulStuInfos" type="button" value="调用GetMulStudentInfos" onclick="BindGetMulStudents();" /> <hr /> </div> <div id="backData"> </div> </body> </html>
2.WebService
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using AjaxDemo.ClassFile; using System.Data; namespace AjaxDemo.Handler { /// <summary> /// UserService 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 [System.Web.Script.Services.ScriptService] public class UserService : System.Web.Services.WebService { /// <summary> /// 返会语句话 /// </summary> [WebMethod] public string HelloWebService() { return "Hello WebService"; } /// <summary> /// 返回一句问候,根据名称 /// </summary> [WebMethod] public string HelloSomeBody(string name) { return "Hello " + name; } /// <summary> /// 设置学生实体,并返回这个实体 /// </summary> [WebMethod] public Student SetStudentInfo(string name, string sex, int age, int sid) { Student stuInfo = new Student(); stuInfo.Sid = sid; stuInfo.Name = name; stuInfo.Sex = sex; stuInfo.Age = age; return stuInfo; } /// <summary> /// 返回泛型数据 /// </summary> /// <returns></returns> [WebMethod] public List<Student> GetMulStudentInfos() { List<Student> stuList = new List<Student>(); for (int i = 0; i < 10; i++) { Student s = new Student(); s.Sid = i + 1; s.Name = "Tom" + s.Sid; s.Sex = "男"; s.Age = i + 1; stuList.Add(s); } return stuList; } [WebMethod] public string ComplexType(User hero, List<User> users) { return hero.Name + " has " + users.Count + "people !"; } /// <summary> /// 返回XML /// </summary> /// <returns></returns> [WebMethod] public DataSet GetDataSet() { DataSet ds = new DataSet(); DataTable dt = new DataTable(); dt.Columns.Add("ID", Type.GetType("System.String")); dt.Columns.Add("Value", Type.GetType("System.String")); DataRow dr = dt.NewRow(); dr["ID"] = "1"; dr["Value"] = "新年快乐"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["ID"] = "2"; dr["Value"] = "万事如意"; dt.Rows.Add(dr); ds.Tables.Add(dt); return ds; } } }
3. 实体类
public class Student { public int Sid { get; set; } public string Name { get; set; } public string Sex { get; set; } public int Age { get; set; } }
public class User { public string Name { get; set; } public int Age { get; set; } public int ID { get; set; } }