本人的js & jq 一直是菜鸟级别,最近不忙就看了看ajax方面的知识,文中部分内容参考自这里&这里 之前一直用js写ajax现在基于jq实现方便多了~

$.get & $.post 和 $.ajax的区别

之前看过同事写过$.post,而我一直用$.ajax,后来才知道$.get()$.post()都是通过get和post方式来进行异步,$.ajax()说是jquery最底层的ajax实现的,这里我们使用$.ajax的方式实现.

调用无参方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//调用无参方法
$("#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);
        }
    });
})
1
2
3
4
5
6
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string SayHello()
{
    return "Hello Ajax!";
}

这里只列出常用的$.ajax的属性以及方法详情请参考这里

有点类似类似调用WebService,后台方法必须为static,访问范围为protect/public,

WebMethod特性是必须的,这样才能被客户端脚本调用,支持远程调用.

ScriptMethod特性是可选的,用于指定调用方法的 HTTP 谓词(GET 或 POST),以及指定输出格式(JSON或XML)没有此特性,方法则默认只能被HTTP POST方式调用,并且输出将序列化为 JSON.

Asp.net 3.5以上可直接使用以上两个命名空间,Asp.net 2.0需安装Asp.net Ajax,或者单独引用Asp.net Ajax的System.Web.Extensions.dll.

如后台方法无参数,data项可填为"{}"或者直接省略.Asp.net 3.5以上使用返回值,需要加上".d",如以上代码里的"data.d",Asp.net 2.0直接使用"data"就行了.原因可能是两者序列化的方法有所不同.

调用有参方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//调用返回有参方法
$(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);
            }
        });
    });
});
1
2
3
4
5
6
[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);
}

调用返回集合方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//调用返回集合方法
$("#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);
        }
    });
});
1
2
3
4
5
6
7
8
9
10
11
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<string> GetList()
{
    List<string> list = new List<string>
    {
        "a","b","c","d","e","f"
    };
 
    return list;
}

调用返回实体方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$("#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);
        }
    });
});
1
2
3
4
5
6
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Person GetPerson()
{
    return new Person { name = "chenxu" };
}  
1
2
3
4
public class Person
{
    public string name { getset; }
}

调用返回DATASET

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//调用返回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);
            }
        }
    });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[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 一般处理程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//调用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);
        }
    });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/// <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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
<%@ 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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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 { getset; }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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;
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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.

Jquery ajax 学习笔记的更多相关文章

  1. AJax 学习笔记二(onreadystatechange的作用)

    AJax 学习笔记二(onreadystatechange的作用) 当发送一个请求后,客户端无法确定什么时候会完成这个请求,所以需要用事件机制来捕获请求的状态XMLHttpRequest对象提供了on ...

  2. jQuery源代码学习笔记_工具函数_noop/error/now/trim

    jQuery源代码学习笔记_工具函数_noop/error/now/trim jquery提供了一系列的工具函数,用于支持其运行,今天主要分析noop/error/now/trim这4个函数: 1.n ...

  3. AJAX学习笔记——jQuery中的AJAX

    用jQuery实现Ajax jQuery.ajax([settings]) 1.type:类型, "POST"或"GET" ,默认为"GET" ...

  4. jQuery 基础学习笔记总结(一)

    Jquery 学习笔记 总结 感想: 此前在做站点时用到过jquery相关,特别是Ajax相关技术.但是并没有系统的进行学习和了解Jquery的强大的功能,趁这几天跟着资料基本的了解下Jquery的特 ...

  5. jQuery的学习笔记4

    JQuery学习笔记3 2.9属性选择器 属性选择器就是根据元素的属性和属性值作为过滤条件,来匹配对应的DOM元素.属性选择器一般都以中括号作为起止分界符 它的形式如下: [attribute] [a ...

  6. jQuery的学习笔记2

    jQuery学习笔记 Day two Chapter two 选择器 类选择器 语法结构:$(“.classname”) javascript里面没有类选择器所以这个时候使用jQuery会更加的简便 ...

  7. jQuery的学习笔记

    JQuery学习笔记 Chapter one初识jQuery 1.2测试jQuery 在jQuery库中,$是jQuery的别名,如:$()相当于jQuery() 注意:在使用JQuery进行开发的时 ...

  8. Jquery API学习笔记

    学习网站 JQuery API 中文网: http://www.jquery123.com/ 学习一遍API可以更熟练的运用jquery并且拓展思路. 这里只挑选了一些我认为在开发中会用到的一些API ...

  9. Ajax 学习笔记

    什么是 AJAX ? AJAX = 异步 JavaScript 和 XML. AJAX 是一种用于创建快速动态网页的技术. 通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新.这意味 ...

随机推荐

  1. Java开发面试总结

    Java开发面试总结.. ----------------------- java 基础知识点这一块: 1.面向对象的三大特征.(继承,封装,多态) 1.1 在什么样的场合下面会使用到继承 1.2 什 ...

  2. Android系统学习小记

    序言 Android 应用的启动到一个页面显示出来,这个过程涉及到点击事件的处理,以及如何启动一个Activity,启动一个Activity之后,如何将Activity中我们的设置的ContentVi ...

  3. winston写日志(译)

    使用 有两种方式去使用winston,直接通过默认的logger,或者实例化自己的Logger,前者设计的目的是在你的应用程序中共享logger比较方便. 使用默认Logger 使用默认的logger ...

  4. Property和attribute的区别[转]

    Attribute和Property都可以翻译成“属性”,有的地方用Attribute表示“属性”,有的地方又在用Property,初 学者常常在这两个单词间“迷失”,甚至认为二者没有区别,是一样的. ...

  5. mysql中event的用法详解

    一.基本概念mysql5.1版本开始引进event概念.event既“时间触发器”,与triggers的事件触发不同,event类似与linux crontab计划任务,用于时间触发.通过单独或调用存 ...

  6. Android ViewPager sharedpreferences

    http://www.cnblogs.com/dwinter/archive/2012/02/27/AndroidViewPager%E5%A4%9A%E9%A1%B5%E9%9D%A2%E6%BB% ...

  7. Bash 是如何从环境变量中导入函数的

    在上文中曾说到: 所谓的环境变量的真实面目其实就是个任意字符串 Bash 在启动时会将 environ 数组中包含 = 号的字符串导入成为自己的变量 Bash 在启动外部命令时会将自己内部标记为环境变 ...

  8. tyvj1863 [Poetize I]黑魔法师之门

    背景 经过了16个工作日的紧张忙碌,未来的人类终于收集到了足够的能源.然而在与Violet星球的战争中,由于Z副官的愚蠢,地球的领袖applepi被邪恶的黑魔法师Vani囚禁在了Violet星球.为了 ...

  9. 如何取消 DiscuzX 帖子被系统自动隐?

    设置路径: 全局 -> 站点功能 -> 帖子阅读 -> 启用隐藏水帖,选择“否”

  10. 浅谈ASM中的SLB

    接触Azure几个月,总想写点什么,迟迟没有动笔,一是怕自己技术粗鄙,写的东西会令人捧腹,二是工作原因,时间比较匆忙,在此再次声明,以下写的东西都是我个人看法,若有不足,请多多包涵!!! 情景是这样的 ...