Jquery ajax 学习笔记

 本人的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 { get; set; }
}

调用返回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

总结

一开始对data.d的这个d不是很理解,感谢这篇文章的博主,相比较与aspx  ashx只能通过ProcessRequest方法进行输出而不能在内部写static method,如果想在ashx中使用session只要实现IRequiresSessionState接口即可,要不然获取到session会为null.

SourceCode

posted @   陈大欠  阅读(1913)  评论(3编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示