第4章 jQuery Ajax应用

Jquery的几种请求方式,首先介绍它们的参数.
 url(String):发送请求的url地址
 data(Map):(可选)发送给服务器的参数,一般以json(Key/Value)格式发送
 type:data数据类型,一般是"json"或"text"类型.
 callback(Function):回调函数

1 jquery.ajax(options):ajax的核心函数,也是最底层的实现,其它的ajax函数都是它的一个简化调用.
 如下是一个Jquery.ajax()请求的示例:
先在服务器建1个一般处理程序:myHandler.ashx,代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DBUtitly;
using System.Web.Script.Serialization;

namespace ajax_bind.Ajax_bind
{
    /// <summary>
    /// MyHandler 的摘要说明
    /// </summary>
    public class MyHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            List<UserInfo> lst = new List<UserInfo>() { new UserInfo(){UserId=101,Username="小五"},new UserInfo(){UserId=102,Username="小刘"},new UserInfo(){UserId=103,Username="张三"}};
            JavaScriptSerializer js = new JavaScriptSerializer();
            context.Response.Write(js.Serialize(lst));
        }

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

接着页面代码如下:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="../jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $.ajax({
                url: "myHandler.ashx",
                type: "get",
                dataType: "json",
                success: function (data) {
                    $("#select").empty();
                    $("#select").append($("<option>--请选择--</option>"));
                    $(data).each(function (index) {
                    $("#select").append($("<option value='$(this)[0].UserId'>" + $(this)[0].Username + "</option>"));
        //此处也可以写为: 
                   //$.each(data, function (i, item) {
                       //$("<option value='"+item.UserId+"'>"+item.Username+"</option>").appendTo("#select");
                    //});
                        })
                }
            });
        });
    </script>
</head>
<body>
       <select id="select"></select>
</body>
</html>
View Code

Ajax示例二:
页面代码如下:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="../jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#sub").click(function () {
                var name = { "username": $("#txtUsername").val() };
                var str = JSON.stringify(name);    //json.stringify():json对象转换为string字符串,以方便服务器端的获取.string字符串转换为json对象用json.parse()方法.
                $.ajax({
                    url: "Handler1.ashx",
                    type: "get",
                    data: { "usname": str },
                    dataType: "text",
                    success: function (data) {
                        alert(data);

                    }
                })
            });
        });
    </script>
</head>
<body>
    <form action="" id="form1">
        姓名:<input type="text" id="txtUsername"/>
        <input type="submit" id="sub" value="提交"/>
    </form>
</body>
</html>
View Code

服务器端的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace ajax_bind.Ajax提交到服务器
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string name = context.Request.QueryString["usname"];
            JavaScriptSerializer js = new JavaScriptSerializer();
            UserInfo username = (UserInfo)js.Deserialize(name,typeof(UserInfo));    //转换类型
            context.Response.Write(username.Username);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public class UserInfo
        {
            public string Username { get; set; }
        }
    }
}
View Code

2 Jquery.Load(url,[data],[callback]):常用来加载文件.
3 Jquery.get(url,[data],[callback],[type]):服务器端用QueryString获取值,发送get请求时,参数可以直接在url中拼接,如:
 $.get("AjaxGetMethod.aspx?param=btnAjaxGet_click");
 或通过data参数传递
 $.get("AjaxGetMethod.aspx",{"param":"btnAjaxGet_click"});
4 Jquery.post(url,[data],[callback],[type]):服务器端用Form获取值.
5 Jquery.getJSON(url,[data],[callback]);
6 Jquery.getScript(url,[callback]);

 

posted @ 2013-12-22 12:14  mmww  阅读(102)  评论(0)    收藏  举报