天天看點

JQuery.ajax——簡單例子

聲明,轉載自http://blog.163.com/l_gx396696760/blog/static/392282292009102433758634/

注意:(1)JQuery.ajax在前台JQuery語句中url格式為:.aspx/背景方法名。

            (2)背景中供前台調用的

                       [WebMethod]   //不知道為嘛,反正必須得有這句話

                       public static string GetWish(string value1, string value2, string value3, int value4)   //函數必須得是公開、靜态的,還必須得有傳回值

                      {

                                return string.Format("祝您在{3}年裡 {0}、{1}、{2}", value1, value2, value3, value4);

                       }

             (3)我是菜鳥,我說的不知道對不對,請大家多多指教

在default2.aspx中代碼如下:

<%@ 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 id="Head1" runat="server">

    <title>無标題頁</title>

    <script type="text/javascript" src="jQuery.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() {

            $("button").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>

==================================================================================

在default2.aspx.cs中代碼如下:

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.Services;

using System.Web.Services.Protocols;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

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; }

    }

}