zoukankan      html  css  js  c++  java
  • jQuery 原理的模拟代码 5 Ajax

    对于 xhr 对象来说,我们主要通过异步方式访问服务器,在 onreadystatechange 事件中处理服务器回应的内容。简单的 xhr 使用如下所示。

     1 // 创建 XHR 对象
     2 var xhr;
     3 if (window.XMLHttpRequest) {
     4     xhr = new XMLHttpRequest();
     5 }
     6 else if (window.ActiveXObject) {
     7     xhr = new ActiveXObject("Msxml2.XMLHTTP");
     8 }
     9 else {
    10     throw new Error("Ajax is not supported by this browser");
    11 }
    12 
    13 function ready()
    14 {
    15     alert("Start......");
    16                 
    17     // 通过事件来处理异步请求
    18     xhr.onreadystatechange = function()
    19     {
    20         if( xhr.readyState == 4 )
    21         {
    22             alert( "Ready.");
    23             if( xhr.status == 200 )
    24             {
    25                 alert("成功获得服务器返回的结果.");
    26                             
    27                 // 请求结束之后,可以获取服务器返回的内容
    28                 alert( xhr.responseText );
    29                 
    30                 // 获取服务器返回的 json 对象
    31                 var alice = eval( "(" + xhr.responseText + ")"   );
    32                 alert( alice.name );
    33             }
    34         }
    35     };
    36                 
    37     // 设置请求参数
    38     xhr.open("get""data.json" );
    39     xhr.send( null );
    40 }

    jQuery 简单地包装了对 xhr 对象的使用,通过对 jQuery 对象增加常用的访问方法,然后,提供给 jQuery 对象来使用。

     1 // 主要的扩展在 jQuery.ajax 中。
     2 jQuery.extend({     // #6299
     3     // 请求的默认参数
     4     ajaxSettings: {
     5         url: location.href,
     6         type: "GET",
     7         contentType: "application/x-www-form-urlencoded",
     8         data: null,
     9         xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
    10             function () {
    11                 return new window.XMLHttpRequest();
    12             } :
    13             function () {
    14                 try {
    15                     return new window.ActiveXObject("Microsoft.XMLHTTP");
    16                 } catch (e) { }
    17             }
    18         },
    19 
    20     // 用来设置 jQuery.ajaxSettings ,设置请求的参数
    21     ajaxSetup: function (settings) {
    22         jQuery.extend(jQuery.ajaxSettings, settings);
    23     },
    24 
    25     ajax: function (origSettings) {      // 实际的 ajax 函数
    26         var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings);
    27 
    28         // 创建 xhr 对象
    29         xhr = s.xhr();
    30         // 回调函数
    31         var onreadystatechange = xhr.onreadystatechange = function (isTimeout) {
    32             if (xhr.readyState === 4) {
    33                 if (xhr.status == 200) {
    34                     s.success.call(origSettings, xhr.responseText);
    35                 }
    36             }
    37         };
    38         
    39         // 设置请求参数
    40         xhr.open(s.type, s.url);
    41 
    42         // Send the data    发出请求
    43         xhr.send(s.data);
    44 
    45         // return XMLHttpRequest to allow aborting the request etc.
    46         return xhr;
    47     },
    48 
    49     // 使用 get 方式发出 ajax 请求的方法
    50     get: function (url, data, callback, type) {
    51         // shift arguments if data argument was omited
    52         if (jQuery.isFunction(data)) {
    53             type = type || callback;
    54             callback = data;
    55             data = null;
    56         }
    57 
    58         return jQuery.ajax({
    59             type: "GET",
    60             url: url,
    61             data: data,
    62             success: callback,
    63             dataType: type
    64         });
    65     }
    66 
    67 
    68 });       // #6922
    69 
    70 // 扩展 jQuery 对象,增加 load 方法
    71 jQuery.fn.extend(
    72     {
    73         load: function (url) {
    74             var self = this;
    75             jQuery.get(url, function (data) {
    76                 self.each(function () {
    77                     this.innerHTML = data;
    78                 }       
    79             )  
    80             }   
    81         )
    82         }
    83     }
    84 )


    在页面中,可以如下使用。

     1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     2 <html xmlns="http://www.w3.org/1999/xhtml">
     3 <head>
     4     <title></title>
     5 </head>
     6 <body>
     7     <input type="button" id="btn" value="Click me" />
     8     <div id="msg">
     9     </div>
    10     <script src="jQuery-core.js" type="text/javascript"></script>
    11     <script src="jQuery-event-2.js" type="text/javascript"></script>
    12     <script src="jQuery-data.js" type="text/javascript"></script>
    13     <script src="jQuery-extend.js" type="text/javascript"></script>
    14     <script src="jQuery-ajax.js" type="text/javascript"></script>
    15     <script type="text/javascript">
    16 
    17             $("#btn").click(function () {
    18                 $("#msg").load("hello.txt");
    19             })
    20         
    21 
    22     </script>
    23 </body>
    24 </html>
    25 

    jQuery 原理的模拟代码 -0 目录

  • 相关阅读:
    ie6下使PNG背景图片透明的方法
    CSS图片转换成模糊(毛玻璃)效果兼容版
    对象Object下的属性和方法
    Collection 回顾
    Java IO学习笔记:File类
    Android开发之Instrumentation(自动化测试)
    Android开发之ActivityManager
    Android开发之WindowManager详解
    在Intel® Galileo Gen 2开发板上运行Debian操作系统
    VS2008下安装与配置DirectShow SDK 9.0
  • 原文地址:https://www.cnblogs.com/haogj/p/1794618.html
Copyright © 2011-2022 走看看