首页 新闻 会员 周边

前台调用后台方法(javascript调用[WebMethod]方法)不太明白原理,可以根据例子解析下吗?

0
悬赏园豆:20 [已解决问题] 解决于 2012-08-14 15:59
<%@ 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;
        }
    }
}

运行结果:

广州大雄的主页 广州大雄 | 初学一级 | 园豆:188
提问于:2012-08-10 17:25
< >
分享
最佳答案
0

就这样定义的呗,楼主就这样理解呗。

主要是[WebMethod]这个特性的功能

收获园豆:10
chenping2008 | 大侠五级 |园豆:9836 | 2012-08-10 19:37
其他回答(1)
0

度娘 JQUERY WebService看结果

收获园豆:10
八戒的师傅 | 园豆:1472 (小虾三级) | 2012-08-10 21:30
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册