<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="test2.WebForm3" %> <!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 runat="server"> <title>前台调用后台方法</title> <script src="jquery-1.7.2.min.js" type="text/javascript"></script> <script type="text/javascript"> function ADD() { var result = Invoke("WebForm3.aspx/add", { "num1": 4, "num2": 5 }); alert(result.toString()); } function json2str(o) { var arr = []; var fmt = function (s) { if (typeof s == 'object' && s != null) return json2str(s); return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s; } for (var i in o) arr.push("'" + i + "':" + fmt(o[i])); return '{' + arr.join(',') + '}'; } function Invoke(url, param) { var result; $.ajax({ type: "POST", url: url, async: false, data: json2str(param), contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { result = msg.d; }, error: function (r, s, e) { alert(s); } }); return result; } </script> </head> <body> <form id="form1" runat="server"> <div> <input type="button" onclick="ADD()" value="调用函数"> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml; using System.Web.Services; namespace test2 { public partial class WebForm3 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static int add(int num1,int num2) { return num1 + num2; } } }
运行结果:
就这样定义的呗,楼主就这样理解呗。
主要是[WebMethod]这个特性的功能
度娘 JQUERY WebService看结果