Asp.Net+Jquery.Ajax详解1-开篇

来源:岁月联盟 编辑:exp 时间:2012-08-06

目录(已经更新的文章会有连接,从7月25日开始,每2到3天更新一篇):


Asp.Net+Jquery.Ajax详解1-开篇(2012.07.25发)

Asp.Net+Jquery.Ajax详解2-$.Load(2012.07.26发)

Asp.Net+Jquery.Ajax详解3-$.get和$.post(2012.07.30发)

Asp.Net+Jquery.Ajax详解4-$.getJSON(2012.07.31发)

Asp.Net+Jquery.Ajax详解5-$.getScript(2012.08.04发)

Asp.Net+Jquery.Ajax详解6-$.ajaxSetup(2012.08.06发)

Asp.Net+Jquery.Ajax详解7-全局Ajax事件

Asp.Net+Jquery.Ajax详解8-核心$.ajax

Asp.Net+Jquery.Ajax详解9-serialize和serializeArray

Asp.Net+Jquery.Ajax详解10-JSON和XML+写在最后


 

 

写在最前面:

我们学习一个东西,最开始对它没有任何概念,可能会一头扎进去,发现水越来越深,书越学越厚,当我们坚持过了一遍,把自己抽出来,站在一个高度上俯视它的时候,才发现其实就这点东西,学来学去,无非就是搞明白5个问题:它是什么?有什么用?和别的有什么关系?同类中有什么优势?怎么用?

 

 

我写Asp.Net+Jquery.Ajax这一系列文章,更确切的说是整理这一系列文章,更多地侧重于它是什么,怎么用这方面,一方面促进自己学习,另一方面希望对大家有所帮助。至于和别的有什么关系,有什么优势,网上到处都是,大家认为好的东西,你就暂且认为它好,然后去学习它,从这一列文章中,我想你能看出它为什么好。

 

系列文章的框架我已经搭好了,一期草稿也搞定了,还会修订内容.大概2,3天会出一篇。下面是我onenote文档中的截图:

 /

 

 

还是希望你有一些javascript基础,见我的文章《深入浅出javascript》,这个文章也会写下去。

 

进入正题啦!!!

 

————————————

什么是 AJAX ?

 

AJAX = 异步 JavaScript 和 XML。

 

AJAX 是一种用于创建快速动态网页的技术。

 

通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

 

传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。

 

有很多使用 AJAX 的应用程序案例:新浪微博、Google 地图、开心网等等。

 

——————————————来自W3cSchool教程网

 

可以这么说,Ajax使我们的网页更人性化,能获得更好地用户体验。

 

使用Ajax是所有Web开发人员的必修课. 虽然Ajax技术并不复杂, 但是实现方式还是会因为每个开发人员的而有所差异。当我们的代码到处分布着创建XmlHttpRequest对象的函数,写判断请求,写回调函数, 而且一些Ajax程序逻辑性和结构性很差, 让人难懂时,我们会想该怎么统一这些差异呢?

 

这时我们便需要用到jquery库。

jQuery是一个Javascript脚本库. Javascript脚本库类似于.NET的类库, 将一些方法封装在类库中, 方便开发者使用.其中,jQuery提供了一系列Ajax函数来帮助我们统一使用Ajax时的一些差异,而且是跨浏览器的(再也不用为了适应所有浏览器把自己的脚本搞得复杂难看了),并且让调用Ajax变得更加简单,代码更加简洁美观。

 

有对比才有能看出,我们为什么要选择jquery.ajax?

 

使用原始Ajax实例(工具为VS2010):

客户端:

[html] 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="OldAjax.aspx.cs" Inherits="JqueryAjaxTest.OldAjax" %> 
 
<!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 runat="server"> 
    <title>原始Ajax</title> 
    <script src="Scripts/jquery-1.3.2-vsdoc2.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
        $(function () { 
            //为按钮绑定事件。 
            $("#AjaxGetHtml").bind("click", {resultType:"html"}, GetData); 
            $("#AjaxGetJson").bind("click", { resultType: "json" }, GetData); 
        }) 
 
            //用原始AJAX获取服务器数据 
            function GetData(event) { 
 
                    //获取XmlHttpRequest对象 
                    var xmlhttp = new GetAjaxXmlHttpRequest(); 
 
                    //每当 readyState 改变时,就会触发 onreadystatechange 事件 
                    //在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。 
                    xmlhttp.onreadystatechange = function () { 
                        //请求已完成,且响应已就绪  
                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
                            $("#oldAjaxResult").html(xmlhttp.responseText); 
                        } 
 
                    } 
 
                    //设子请求的URL,添加Math.random()避免得到缓存的结果 
                    var url= "Data/GetCity.aspx?resultType=" + event.data.resultType.toString() + "&t=" + Math.random(); 
                  
                    //规定请求的类型、URL 以及是否异步处理请求。 
                    xmlhttp.open("GET", url, true);   
              
                    //将请求发送到服务器 
                    xmlhttp.send(); 
                }; 
             
             
            //跨浏览器获取XmlHttpRequest对象 
            function GetAjaxXmlHttpRequest() { 
 
                var xmlhttp; 
                try { 
                    if (window.XMLHttpRequest) { 
                        //for for IE7+, Firefox, Chrome, Opera, Safari 
                        xmlhttp = new XMLHttpRequest(); 
                    } else { 
                        //for IE5,6 
                        xmlhttp = new ActiveXObject("Microsoft.XmlHttp"); 
                    } 
 
                } catch (e) { 
                    alert("您的浏览器不支持AJAX!"); 
                    return false; 
 
                } 
 
                return xmlhttp; 
 
            } 
 
         
    </script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
       <input id="AjaxGetHtml" type="button" value="AjaxGetHtml" /> 
        <input id="AjaxGetJson" type="button" value="AjaxGetJson" /> 
        <div id="oldAjaxResult"></div> 
    </div> 
    </form> 
</body> 
</html> 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="OldAjax.aspx.cs" Inherits="JqueryAjaxTest.OldAjax" %>

<!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 runat="server">
    <title>原始Ajax</title>
    <script src="Scripts/jquery-1.3.2-vsdoc2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            //为按钮绑定事件。
            $("#AjaxGetHtml").bind("click", {resultType:"html"}, GetData);
            $("#AjaxGetJson").bind("click", { resultType: "json" }, GetData);
        })

            //用原始AJAX获取服务器数据
            function GetData(event) {

                    //获取XmlHttpRequest对象
                    var xmlhttp = new GetAjaxXmlHttpRequest();

                    //每当 readyState 改变时,就会触发 onreadystatechange 事件
                    //在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。
                    xmlhttp.onreadystatechange = function () {
                        //请求已完成,且响应已就绪
                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                            $("#oldAjaxResult").html(xmlhttp.responseText);
                        }

                    }

                    //设子请求的URL,添加Math.random()避免得到缓存的结果
                    var url= "Data/GetCity.aspx?resultType=" + event.data.resultType.toString() + "&t=" + Math.random();
                
                    //规定请求的类型、URL 以及是否异步处理请求。
                    xmlhttp.open("GET", url, true); 
            
                    //将请求发送到服务器
                    xmlhttp.send();
                };
           
           
            //跨浏览器获取XmlHttpRequest对象
            function GetAjaxXmlHttpRequest() {

                var xmlhttp;
                try {
                    if (window.XMLHttpRequest) {
                        //for for IE7+, Firefox, Chrome, Opera, Safari
                        xmlhttp = new XMLHttpRequest();
                    } else {
                        //for IE5,6
                        xmlhttp = new ActiveXObject("Microsoft.XmlHttp");
                    }

                } catch (e) {
                    alert("您的浏览器不支持AJAX!");
                    return false;

                }

                return xmlhttp;

            }

       
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <input id="AjaxGetHtml" type="button" value="AjaxGetHtml" />
        <input id="AjaxGetJson" type="button" value="AjaxGetJson" />
        <div id="oldAjaxResult"></div>
    </div>
    </form>
</body>
</html>
服务端:

[csharp] 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
 
namespace JqueryAjaxTest.Data 

    public partial class GetCity : System.Web.UI.Page 
    { 
        private string resultType = "json"; 
        protected void Page_Load(object sender, EventArgs e) 
        { 
            //获取请求的参数  
            if (!String.IsNullOrEmpty(Request.QueryString["resultType"])) { 
 
                resultType = Request.QueryString["resultType"].ToLower()=="html" ? "html" : "json"; 
            } 
           string  html = GetResult(resultType); 
 
           //清空缓冲区  
           Response.Clear(); 
           //将字符串写入响应输出流  
           Response.Write(html); 
           //将当前所有缓冲的输出发送的客户端,并停止该页执行  
           Response.End(); 
        } 
 
        private string GetResult(string resultType) { 
            string result = ""; 
            if (resultType == "html") { 
 
               //返回的html  
                result = @"<ul><li id=""1"">北京</li><li id=""2"">天津</li></ul>"; 
            } 
            else if (resultType == "json") { 
                //返回的json数据  
                result = @" 
[{""pkid"":""0001"",""ProvinceId"":""BJ"",""CityName"":""北京"",""CityNameEn"":""Beijing"",""PostCode"":""010"",""isHotCity"":false}, 
 {""pkid"":""0002"",""ProvinceId"":""TJ"",""CityName"":""天津"",""CityNameEn"":""Tianjin"",""PostCode"":""022"",""isHotCity"":false}]"; 
                   
            } 
            return result; 
        } 
    } 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace JqueryAjaxTest.Data
{
    public partial class GetCity : System.Web.UI.Page
    {
        private string resultType = "json";
        protected void Page_Load(object sender, EventArgs e)
        {
            //获取请求的参数
            if (!String.IsNullOrEmpty(Request.QueryString["resultType"])) {

                resultType = Request.QueryString["resultType"].ToLower()=="html" ? "html" : "json";
            }
           string  html = GetResult(resultType);

           //清空缓冲区
           Response.Clear();
           //将字符串写入响应输出流
           Response.Write(html);
           //将当前所有缓冲的输出发送的客户端,并停止该页执行
           Response.End();
        }

        private string GetResult(string resultType) {
            string result = "";
            if (resultType == "html") {

               //返回的html
                result = @"<ul><li id=""1"">北京</li><li id=""2"">天津</li></ul>";
            }
            else if (resultType == "json") {
                //返回的json数据
                result = @"
[{""pkid"":""0001"",""ProvinceId"":""BJ"",""CityName"":""北京"",""CityNameEn"":""Beijing"",""PostCode"":""010"",""isHotCity"":false},
 {""pkid"":""0002"",""ProvinceId"":""TJ"",""CityName"":""天津"",""CityNameEn"":""Tianjin"",""PostCode"":""022"",""isHotCity"":false}]";
                 
            }
            return result;
        }
    }
}
 

使用Jquery.ajax的方法,我们会在后面的文章中陆续讲到,你会渐渐明白为什么要选择Jquery.ajax

 

最后附上这一系列文章的大体框架(思维导图):

 

 /
作者:shan9liang