Jquery ajax 學習筆記

 本人的js & jq 一直是菜鳥級別,最近不忙就看了看ajax方面的知識,文中部份內容參考自這裏&這裏 以前一直用js寫ajax如今基於jq實現方便多了~javascript

$.get & $.post 和 $.ajax的區別html

以前看過同事寫過$.post,而我一直用$.ajax,後來才知道$.get()$.post()都是經過get和post方式來進行異步,$.ajax()說是jquery最底層的ajax實現的,這裏咱們使用$.ajax的方式實現.java

調用無參方法jquery

//調用無參方法
$("#Button1").click(function () {
    $.ajax({
        //要用post方式      
        type: "Post",
        //方法所在頁面和方法名      
        url: "About.aspx/SayHello",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            //返回的數據用data.d獲取內容      
            alert(data.d);
        },
        error: function (err) {
            alert("Error: " + err);
        }
    });
})
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string SayHello()
{
    return "Hello Ajax!";
}

這裏只列出經常使用的$.ajax的屬性以及方法詳情請參考這裏web

有點相似相似調用WebService,後臺方法必須爲static,訪問範圍爲protect/public,ajax

WebMethod特性是必須的,這樣才能被客戶端腳本調用,支持遠程調用.json

ScriptMethod特性是可選的,用於指定調用方法的 HTTP 謂詞(GET 或 POST),以及指定輸出格式(JSON或XML)沒有此特性,方法則默認只能被HTTP POST方式調用,而且輸出將序列化爲 JSON.session

Asp.net 3.5以上可直接使用以上兩個命名空間,Asp.net 2.0需安裝Asp.net Ajax,或者單獨引用Asp.net Ajax的System.Web.Extensions.dll.app

如後臺方法無參數,data項可填爲"{}"或者直接省略.Asp.net 3.5以上使用返回值,須要加上".d",如以上代碼裏的"data.d",Asp.net 2.0直接使用"data"就好了.緣由多是二者序列化的方法有所不一樣.異步

調用有參方法

//調用返回有參方法
$(function () {
    $("#Button2").click(function () {
        $.ajax({
            type: "Post",
            url: "About.aspx/Hello",
            //方法傳參的寫法必定要對,name爲形參的名字,age爲第二個形參的名字      
            data: "{'name':'chenxu','age':'21'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                //返回的數據用data.d獲取內容      
                alert(data.d);
            },
            error: function (err) {
                alert("Error: " + err);
            }
        });
    });
});
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Hello(string name, string age)
{
    return string.Format("hello my name is {0}, {1} years old.", name, age);
}

調用返回集合方法

//調用返回集合方法
$("#Button3").click(function () {
    $.ajax({
        type: "Post",
        url: "About.aspx/GetList",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            //插入前先清空ul      
            $("#list").html("");

            //遞歸獲取數據      
            $(data.d).each(function () {
                //插入結果到li裏面      
                $("#list").append("<li>" + this + "</li>");
            });

            alert(data.d);
        },
        error: function (err) {
            alert("Error: " + err);
        }
    });
});
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<string> GetList()
{
    List<string> list = new List<string>
    {
        "a","b","c","d","e","f"
    };

    return list;
}

調用返回實體方法

$("#Button4").click(function () {
    $.ajax({
        type: "Post",
        url: "About.aspx/GetPerson",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            $(data.d).each(function () {
                alert(this["name"]);
            })
        },
        error: function (err) {
            alert("Error: " + err);
        }
    });
});
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Person GetPerson()
{
    return new Person { name = "chenxu" };
}  
public class Person
{
    public string name { get; set; }
}

調用返回DATASET

//調用返回DATASET方法
$('#Button5').click(function () {
    $.ajax({
        type: "POST",
        url: "WebService.asmx/GetDataSet",
        //data: "{}",
        dataType: 'xml', //返回的類型爲XML 
        success: function (result) { //成功時執行的方法 
            //捕獲處理過程當中的異常並輸出 
            try {
                $(result).find("Table1").each(function () {
                    alert($(this).find("Id").text() + " " + $(this).find("Value").text());
                });
            }
            catch (e) {
                alert(e);
                return;
            }
        },
        error: function (result, status) { //出錯時會執行這裏的回調函數 
            if (status == 'error') {
                alert(status);
            }
        }
    });
});
[WebMethod]
//[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
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"] = ".NET";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr["ID"] = "2";
    dr["Value"] = "JAVA";
    dt.Rows.Add(dr);
    ds.Tables.Add(dt);

    return ds;
}

調用dataset老是出問題,以前記得這樣寫是好用的,找了好長時間沒找到問題,哪位大神找到了告訴我.

把web form裏面的方法GetDataSet放到web service(asmx)中 並設定 contentType: "text/xml; charset=utf-8",dataType: 'xml' 

調用ASHX 通常處理程序

//調用ASHX 通常處理程序
$("#Button6").click(function () {
    $.ajax({
        type: "Post",
        url: "Hello.ashx",
        contentType: "application/json; charset=utf-8",
        dataType: "html", //此處須要寫成html
        success: function (data) {
            alert(data);
        },
        error: function (err) {
            alert("Error: " + err);
        }
    });
});
/// <summary>
/// Hello 的摘要說明
/// </summary>
public class Hello : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
        context.Response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

完整code

<%@ Page Title="主頁" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="JqueryAjax._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {

            //調用無參方法
            $("#Button1").click(function () {
                $.ajax({
                    //要用post方式      
                    type: "Post",
                    //方法所在頁面和方法名      
                    url: "About.aspx/SayHello",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        //返回的數據用data.d獲取內容      
                        alert(data.d);
                    },
                    error: function (err) {
                        alert("Error: " + err);
                    }
                });
            })

            //調用返回有參方法
            $(function () {
                $("#Button2").click(function () {
                    $.ajax({
                        type: "Post",
                        url: "About.aspx/Hello",
                        //方法傳參的寫法必定要對,str爲形參的名字,str2爲第二個形參的名字      
                        data: "{'name':'chenxu','age':'21'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            //返回的數據用data.d獲取內容      
                            alert(data.d);
                        },
                        error: function (err) {
                            alert("Error: " + err);
                        }
                    });
                });
            });

            //調用返回集合方法
            $("#Button3").click(function () {
                $.ajax({
                    type: "Post",
                    url: "About.aspx/GetList",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        //插入前先清空ul      
                        $("#list").html("");

                        //遞歸獲取數據      
                        $(data.d).each(function () {
                            //插入結果到li裏面      
                            $("#list").append("<li>" + this + "</li>");
                        });

                        alert(data.d);
                    },
                    error: function (err) {
                        alert("Error: " + err);
                    }
                });
            });

            //調用返回實體方法
            $("#Button4").click(function () {
                $.ajax({
                    type: "Post",
                    url: "About.aspx/GetPerson",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        $(data.d).each(function () {
                            alert(this["name"]);
                        })
                    },
                    error: function (err) {
                        alert("Error: " + err);
                    }
                });
            });

            //調用返回DATASET方法
            $('#Button5').click(function () {
                $.ajax({
                    type: "POST",
                    url: "WebService.asmx/GetDataSet",
                    //data: "{}",
                    dataType: 'xml', //返回的類型爲XML 
                    success: function (result) { //成功時執行的方法 
                        //捕獲處理過程當中的異常並輸出 
                        try {
                            $(result).find("Table1").each(function () {
                                alert($(this).find("Id").text() + " " + $(this).find("Value").text());
                            });
                        }
                        catch (e) {
                            alert(e);
                            return;
                        }
                    },
                    error: function (result, status) { //出錯時會執行這裏的回調函數 
                        if (status == 'error') {
                            alert(status);
                        }
                    }
                });
            });

            //調用ASHX 通常處理程序
            $("#Button6").click(function () {
                $.ajax({
                    type: "Post",
                    url: "Hello.ashx",
                    contentType: "application/json; charset=utf-8",
                    dataType: "html", //此處須要寫成html
                    success: function (data) {
                        alert(data);
                    },
                    error: function (err) {
                        alert("Error: " + err);
                    }
                });
            });
        })
    </script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        ASP.NET Jquery Ajax 調用後臺方法示例.
    </h2>
    <input id="Button1" type="button" value="調用無參方法" />
    <input id="Button2" type="button" value="調用有參方法" />
    <input id="Button3" type="button" value="調用返回集合方法" />
    <input id="Button4" type="button" value="調用返回實體方法" />
    <input id="Button5" type="button" value="調用返回DATASET方法" />
    <input id="Button6" type="button" value="調用ASHX" />
    <ul id="list">
    </ul>
</asp:Content>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data;

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

        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string SayHello()
        {
            return "Hello Ajax!";
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string Hello(string name, string age)
        {
            return string.Format("hello my name is {0}, {1} years old.", name, age);
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List<string> GetList()
        {
            List<string> list = new List<string>
         {
            "a","b","c","d","e","f"
         };

            return list;
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static Person GetPerson()
        {
            return new Person { name = "chenxu" };
        } 
    }

    public class Person
    {
        public string name { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace JqueryAjax
{
    /// <summary>
    /// Hello 的摘要說明
    /// </summary>
    public class Hello : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;

/// <summary>
///WebService 的摘要說明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要容許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消對下行的註釋。 
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{

    public WebService()
    {
    }

    [WebMethod]
    public DataSet GetDataSet()
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        dt.Columns.Add("Id", Type.GetType("System.String"));
        dt.Columns.Add("Vlues", Type.GetType("System.String"));
        DataRow dr = dt.NewRow();
        dr["Id"] = "小花";
        dr["Vlues"] = "aaaaaaaaa";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr["Id"] = "小兵";
        dr["Vlues"] = "bbbbbbbbb";
        dt.Rows.Add(dr);
        ds.Tables.Add(dt);
        return ds;
    }
}

總結

一開始對data.d的這個d不是很理解,感謝這篇文章的博主,相比較與aspx  ashx只能經過ProcessRequest方法進行輸出而不能在內部寫static method,若是想在ashx中使用session只要實現IRequiresSessionState接口便可,要否則獲取到session會爲null.

SourceCode

相關文章
相關標籤/搜索