一、三种情况的服务端
1.可以调用aspx.cs 中声明带有[WebMehtod]的public static 的方法(不需要自己手动添加web.config的配置)
2.可以调用 *.asmx (web服务) 里面加了[webmethod]的方法(不能写静态,写静态就调用不到了)需要在asmx里面 去掉 [System.Web.Script.Services.ScriptService] 的注释
3.可以调用 *.ashx (一般处理程序),它和aspx一样都实现了IHttpHandler接口。
二、前台请求的要求
type:请求的类型,这里必须用post 。WebMethod方法只接受post类型的请求。
contentType:发送信息至服务器时内容编码类型。我们这里一定要用 application/json 。
url:请求的服务器端处理程序的路径,格式为"文件名(含后缀)/方法名"
data:参 数列表。注意,这里的参数一定要是json格式的字符串,记住是字符串格式,如:"{aa:11,bb:22,cc:33 , …}"。如果你写的不是字符串,那jquery会把它实序列化成字符串,那么在服务器端接受到的就不是json格式了。
dataType:服务器返回的数据类型。必须是json,其他的都无效。因为 webservice 是一json格式返回数据的,其形式为:{“d”:"…"}。
success:请求成功后的回调函数。你 可以在这里对返回的数据做任意处理。
三、代码示例(主要是aspx.cs方法的调用)
1.返回Model
- 后台方法
/// <summary>
/// 返回Model
/// </summary>
/// <returns></returns>
[WebMethod]
public static object Get()
{
return
new
{
code = 0,
msg = "",
count = 10,
data = new List<object>(){new{
id = "1",
username = "",
email = "",
sex = "",
city = "",
experience = ""
}}
};
}
- 前台方法
$.ajax({
url: "/Default.aspx/Get",
dataType: "json",
type: "post",
contentType: 'application/json',
success: function (res) {
console.log("返回Model")
console.log(res)
}, error: (res) => {
console.log("错误")
console.log(res)
}
})
- 数据
2.传参调用
- 后台方法
/// <summary>
/// 传参
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
[WebMethod]
public static int GetInt(int a)
{
return a;
}
- 前台方法
$.ajax({
url: "/Default.aspx/GetInt",
dataType: "json",
type: "post",
data: '{a:1}',
contentType: 'application/json',
success: function (res) {
console.log("传参")
console.log(res)
}, error: (res) => {
console.log("错误")
console.log(res)
}
})
- 数据
3.返回列表
- 后台方法
/// <summary>
/// 获取列表
/// </summary>
[WebMethod]
public static List<int> GetList()
{
return new List<int>() {
1,2,3
};
}
- 前台方法
$.ajax({
url: "/Default.aspx/GetList",
dataType: "json",
type: "post",
contentType: 'application/json',
success: function (res) {
console.log("返回列表")
console.log( res)
}, error: (res) => {
console.log("错误")
console.log(res)
}
})
- 前台数据
四、前台JS封装
对上面的函数做一下简单的封装:
我们建一个脚本文件叫 jquery.extend.js。在里面写一个叫ajaxWebService的方法(因为webmethod其实就是WebService嘛,故此方 法对请求*.asmx也是有效的),代码如下:
$.ajaxWebService = function (url, dataMap, fnSuccess) {
$.ajax({
type: "POST",
contentType: "application/json",
url: url,
data: dataMap,
dataType: "json",
success: fnSuccess
});
}
好了,这样我们请求webmethod方法 就可以这样写了:
$.ajaxWebService("WebForm2.aspx/GetUserName", "{}", function(result) {......});