jquery调用asp.net 页面后台方法

本章将和大家一起学习,在asp.net 页面如何使用jquery调用asp.net 页面后台代码.

废话不多说,我们马上进入正题!

   先创建一个aspx页面编写一个客户端控件<input type="button" id="AjaxDemo" value="AjaxDemo">

再aspx后台的页面编写一个简单的方法,代码如下:

[WebMethod]
public static string ABC(string ABC)
{
    return ABC;
}

必须声明为静态方法,并且它们必须使用 [WebMethod] 特性标注。

接下来就应该考虑怎么让前台的客户端控件调用到后台的方法了..这时jqury登场了..

在页面引入jquery类库

<script type="text/javascript" src="JQuery/jquery-1.3.2-vsdoc2.js"></script>

在页面添加脚本代码如下:

<script type="text/javascript">

$().ready(
            function() {
                $("#AjaxDemo").click(function() {
                    $.ajax({
                        type: "POST",
                        url: "Default.aspx/ABC",
                        data: "{'ABC':'test'}",
                        contentType: "application/json; charset=utf-8",
                        success: function(msg) {alert(msg); }
                    })
                })
            }
        )

</script >

这样就大功告成了!很多事情都是jquery类库帮我们做完了,我们这里讨论的是如何用,具体里面怎么实现,我们不关心!

jquery里还有很多像$.ajax这样的方法提供给我们使用.大家可以试试!

PS:本人也只是初学,这里只是做下笔记!如果讲得有什么不对,请大家指出来!

补充:注意要建3.5的项目,如果是2.0的话。配置文件会少很多引用的,如果你建的是2.0项目的话。建个3.5的。把3.5的配置文件覆盖到2.0的项目即可!

上面的代码如果成功之后弹出的是"{d:test}",是因为他返回的是字符串,我们可以将他改成返回json对象.

把jquery代码修改如下

$().ready(
            function() {
                $("#AjaxDemo").click(function() {
                    $.ajax({
                        type: "POST",
                        url: "Default.aspx/ABC",
                        data: "{'ABC':'test'}",
                        dataType: "json",
                        contentType: "application/json; charset=utf-8",
                        success: function(msg) {alert(msg.d); }
                    })
                })
            }
        )

我们设置他返回的数据是json对象,现在我们可以用返回的json对象,根据弹出来的d:test,我们可以很明显看到key是d,值是test,那我们利用返回的数据msg对象直接点d,就可以获得test的,修改了代码之后.现在弹出来就是test了..

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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>
    <style type="text/css">
   
     .hover
        {
            cursor: pointer; /*小手*/
            background: #ffc; /*背景*/
        }

    </style>
    <script type="text/javascript" src="js/jquery-1.3.2-vsdoc2.js"></script>
     <script type="text/javascript">


        //无参数调用
        $(document).ready(function() {
            $('#btn1').click(function() {
                $.ajax({
                    type: "POST",   //访问WebService使用Post方式请求
                    contentType: "application/json", //WebService 会返回Json类型
                    url: "Default2.aspx/HelloWorld", //调用WebService的地址和方法名称组合 ---- WsURL/方法名
                    data: "{}",         //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到      
                    dataType: 'json',
                    success: function(result) {     //回调函数,result,返回值
                        alert(result.d);
                    }
                });
            });
        });


        //有参数调用
        $(document).ready(function() {
            $("#btn2").click(function() {
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "Default2.aspx/GetWish",
                    data: "{value1:'心想事成',value2:'万事如意',value3:'牛牛牛',value4:2009}",
                    dataType: 'json',
                    success: function(result) {
                        alert(result.d);
                    }
                });
            });
        });
       
       
        //返回集合(引用自网络,很说明问题)
        $(document).ready(function() {
            $("#btn3").click(function() {
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "Default2.aspx/GetArray",
                    data: "{i:10}",
                    dataType: 'json',
                    success: function(result) {
                        $(result.d).each(function() {
                            alert(this);
                            $('#dictionary').append(this.toString() + " ");
                            //alert(result.d.join(" | "));
                        });
                    }
                });
            });
        });


        //返回复合类型
        $(document).ready(function() {
            $('#btn4').click(function() {
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "Default2.aspx/GetClass",
                    data: "{}",
                    dataType: 'json',
                    success: function(result) {
                        $(result.d).each(function() {
                            //alert(this);
                            $('#dictionary').append(this['ID'] + " " + this['Value']);
                            //alert(result.d.join(" | "));
                        });

                    }
                });
            });
        });

        //返回DataSet(XML)
        $(document).ready(function() {
            $('#btn5').click(function() {
                $.ajax({
                    type: "POST",
                    url: "Default2.aspx/GetDataSet",
                    data: "{}",
                    dataType: 'xml', //返回的类型为XML ,和前面的Json,不一样了
                    success: function(result) {
                    alert(result);
                    //演示一下捕获
                        try {  
                            $(result).find("Table1").each(function() {
                                $('#dictionary').append($(this).find("ID").text() + " " + $(this).find("Value").text());
                            });
                        }
                        catch (e) {
                            alert(e);
                            return;
                        }
                    },
                    error: function(result, status) { //如果没有上面的捕获出错会执行这里的回调函数
                        if (status == 'error') {
                            alert(status);
                        }
                    }
                });
            });
        });

        //Ajax 为用户提供反馈,利用ajaxStart和ajaxStop 方法,演示ajax跟踪相关事件的回调,他们两个方法可以添加给jQuery对象在Ajax前后回调
        //但对与Ajax的监控,本身是全局性的
        $(document).ready(function() {
            $('#loading').ajaxStart(function() {
                $(this).show();
            }).ajaxStop(function() {
                $(this).hide();
            });
        });

        // 鼠标移入移出效果,多个元素的时候,可以使用“,”隔开
        $(document).ready(function() {
            $('btn').hover(function() {
                $(this).addClass('hover');
            }, function() {
                $(this).removeClass('hover');
            });
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" id="btn1" value="HelloWorld"/>
    <input type="button" id="btn2" value="传入参数"/>
    <input type="button" id="btn3" value="返回集合"/>
    <input type="button" id="btn4" value=" 返回复合类型"/>
    <input type="button" id="btn5" value="返回DataSet(XML)"/>
    </div>
    <div id="dictionary">dictionary
    </div>
    </form>
</body>
</html>
==================================================================================

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.Services;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    public static string HelloWorld()
    {
        return "123--->456";
    }
    [WebMethod]
    public static string ABC(string ABC)
    {
        return ABC;
    }
    [WebMethod]
    public static string GetWish(string value1, string value2, string value3, int value4)
    {
        return string.Format("祝您在{3}年里 {0}、{1}、{2}", value1, value2, value3, value4);
    }
    /// <summary>
    /// 返回集合
    /// </summary>
    /// <param name="i"></param>
    /// <returns></returns>
    [WebMethod]
    public static List<int> GetArray(int i)
    {
        List<int> list = new List<int>();

        while (i >= 0)
        {
            list.Add(i--);
        }

        return list;
    }

    /// <summary>
    /// 返回一个复合类型
    /// </summary>
    /// <returns></returns>
    [WebMethod]
    public static Class1 GetClass()
    {
        return new Class1 { ID = "1", Value = "牛年大吉" };
    }


    /// <summary>
    /// 返回XML
    /// </summary>
    /// <returns></returns>
    [WebMethod]
    public static 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;
    }
    public class Class1
    {
        public string ID { get; set; }
        public string Value { get; set; }
    }

}

转自:http://blog.163.com/ganlanfei@126/blog/static/121819871200982681729516/

posted on 2011-08-26 16:34  Allen_Chang  阅读(637)  评论(0编辑  收藏  举报

导航