klvoek

klvoek

(十三)jQuery的Ajax功能扩展代码

看了一边Ajax功能模块代码的实现,最后倒叙查看代码。

最后面httpData 和 param两个函数的实现比较简单。

// Get the data out of an XMLHttpRequest. // Return parsed XML if content-type header is "xml" and type is "xml" or omitted, // otherwise return plain text. httpData: function(r,type) {
    var ct = r.getResponseHeader("content-type");
    var data = !type && ct && ct.indexOf("xml") >= 0;
    data = type == "xml" || data ? r.responseXML : r.responseText;
    // If the type is "script", eval it     if ( type == "script" ) eval.call( window, data );
    return data;
},// Serialize an array of form elements or a set of // key/values into a query string param: function(a) {
    var s = [];
     
    // If an array was passed in, assume that it is an array     // of form elements     if ( a.constructor == Array ) {
        // Serialize the form elements         for ( var i = 0; i < a.length; i++ )
            s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
         
    // Otherwise, assume that it's an object of key/value pairs     } else {
        // Serialize the key/values         for ( var j in a )
            s.push( j + "=" + encodeURIComponent( a[j] ) );
    }
     
    // Return the resulting serialization     return s.join("&");
}

httpData的参数r为response,type是响应内容的格式。当没有指定type的时候则获取响应中指定的类型(仅判断是否是xml,如果不是则把响应内容当作文本处理)。如果指明type类型为script,则使用eval执行。httpData里区分了三种类型 text、xml、script[javascript]

param方法是将传入的请求数据构造成请求字符串。这里面用到了数组的push和join方法。encodeURIComponent方法是JavaScript内置方法。原来param方法实现这么简单,以前还一直觉得ajax接口传递对象或者数组很神奇的。

在向上看的时候发现了httpSuccess、httpIsModified用于判断请求是否成功以及指定的url的内容是否发生修改。简单代码看看呗:

// Counter for holding the number of active queries active: 0,// Determines if an XMLHttpRequest was successful or not httpSuccess: function(r) {
    try {
        return !r.status && location.protocol == "file:" ||
            ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
            jQuery.browser.safari && r.status == undefined;
    } catch(e){}
    return false;
},// Determines if an XMLHttpRequest returns NotModified httpNotModified: function(xml, url) {
    try {
        var xmlRes = xml.getResponseHeader("Last-Modified");
        // Firefox always returns 200. check Last-Modified date         return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
            jQuery.browser.safari && xml.status == undefined;
    } catch(e){}
    return false;
}

看看httpSuccess判断是否响应成功兼容浏览器的实现。httpNotModified如何判断请求是否返回了未修改的消息。active记录了当前活动态的请求数。

// Last-Modified header cache for next request lastModified: {},
ajax: function( type, url, data, ret, ifModified ) {
    // If only a single argument was passed in,     // assume that it is a object of key/value pairs     if ( !url ) {
        ret = type.complete;
        var success = type.success;
        var error = type.error;
        data = type.data;
        url = type.url;
        type = type.type;
    }
     
    // Watch for a new set of requests     if ( ! jQuery.active++ )
        jQuery.event.trigger( "ajaxStart" );
    var requestDone = false;
    // Create the request object     var xml = new XMLHttpRequest();
    // Open the socket     xml.open(type || "GET", url, true);
     
    // Set the correct header, if data is being sent     if ( data )
        xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
     
    // Set the If-Modified-Since header, if ifModified mode.     if ( ifModified )
        xml.setRequestHeader("If-Modified-Since",
            jQuery.lastModified[url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
     
    // Set header so calling script knows that it's an XMLHttpRequest     xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    // Make sure the browser sends the right content length     if ( xml.overrideMimeType )
        xml.setRequestHeader("Connection", "close");
     
    // Wait for a response to come back     var onreadystatechange = function(istimeout){
        // The transfer is complete and the data is available, or the request timed out         if ( xml && (xml.readyState == 4 || istimeout == "timeout") ) {
            requestDone = true;
            var status = jQuery.httpSuccess( xml ) && istimeout != "timeout" ?
                ifModified && jQuery.httpNotModified( xml, url ) ? "notmodified" : "success" : "error";
             
            // Make sure that the request was successful or notmodified             if ( status != "error" ) {
                // Cache Last-Modified header, if ifModified mode.                 var modRes = xml.getResponseHeader("Last-Modified");
                if ( ifModified && modRes ) jQuery.lastModified[url] = modRes;
                 
                // If a local callback was specified, fire it                 if ( success ) success( xml, status );
                 
                // Fire the global callback                 jQuery.event.trigger( "ajaxSuccess" );
             
            // Otherwise, the request was not successful             } else {
                // If a local callback was specified, fire it                 if ( error ) error( xml, status );
                 
                // Fire the global callback                 jQuery.event.trigger( "ajaxError" );
            }
             
            // The request was completed             jQuery.event.trigger( "ajaxComplete" );
             
            // Handle the global AJAX counter             if ( ! --jQuery.active )
                jQuery.event.trigger( "ajaxStop" );
            // Process result             if ( ret ) ret(xml, status);
             
            // Stop memory leaks             xml.onreadystatechange = function(){};
            xml = null;
             
        }
    };
    xml.onreadystatechange = onreadystatechange;
     
    // Timeout checker     if(jQuery.timeout > 0)
        setTimeout(function(){
            // Check to see if the request is still happening             if (xml) {
                // Cancel the request                 xml.abort();
                if ( !requestDone ) onreadystatechange( "timeout" );
                // Clear from memory                 xml = null;
            }
        }, jQuery.timeout);
     
    // Send the data     xml.send(data);
}

从第一行开始看。如果只传入了一个参数则认为传入的是一个参数对象,获取对象传递的参数。

第二行判断是否开始一批新的请求,如果是的话则触发ajaxStart事件。注意这里trigger的使用,触发了全局的事件,所有的监听者都会监听。

开始请求并设置请求的参数,定义请求状态变化时的响应方法并绑定。

如果给定了超时时间设置设置超时监听方法。在超时时进行超时处理。

发送ajax请求。

先分析超时响应的方法代码,判断当前的请求对象是否存在,如果存在则退出当前请求。调用onreadystatechange('timeout')。

onreadystatechange方法。获取请求状态,如果请求状态是成功的则设置请求地址的最近修改时间,如果设置了请求完成的处理方法则调用该方法,触发全局的ajaxSuccess事件。如果没有成功,如果设置了失败的处理方法则调用该方法,触发全局的ajaxError事件。

触发全局的ajaxComplete事件。如果再没有了ajax请求则触发ajaxStop事件。 后两个代码清处理内存问题。

向上看,还有简单代码:

// timeout (ms) timeout: 0,
ajaxTimeout: function(timeout) {
    jQuery.timeout = timeout;
},

再向上看:

get: function( url, data, callback, type, ifModified ) {
    if ( data.constructor == Function ) {
        type = callback;
        callback = data;
        data = null;
    }
     
    if ( data ) url += "?" + jQuery.param(data);
     
    // Build and start the HTTP Request     jQuery.ajax( "GET", url, null, function(r, status) {
        if ( callback ) callback( jQuery.httpData(r,type), status );
    }, ifModified);
},
getIfModified: function( url, data, callback, type ) {
    jQuery.get(url, data, callback, type, 1);
},
getScript: function( url, data, callback ) {
    jQuery.get(url, data, callback, "script");
},
post: function( url, data, callback, type ) {
    // Build and start the HTTP Request     jQuery.ajax( "POST", url, jQuery.param(data), function(r, status) {
        if ( callback ) callback( jQuery.httpData(r,type), status );
    });
}

这几个方法是对ajax方法的封装。

对jQuery.fn上ajax相关方法的扩展以及ie兼容的XMLHttpRequest创建代码不在介绍。

jQuery.fn.loadIfModified = function( url, params, callback ) {
    this.load( url, params, callback, 1 );
};
jQuery.fn.load = function( url, params, callback, ifModified ) {
    if ( url.constructor == Function )
        return this.bind("load", url);
    callback = callback || function(){};
    // Default to a GET request     var type = "GET";
    // If the second parameter was provided     if ( params ) {
        // If it's a function         if ( params.constructor == Function ) {
            // We assume that it's the callback             callback = params;
            params = null;
             
        // Otherwise, build a param string         } else {
            params = jQuery.param( params );
            type = "POST";
        }
    }
     
    var self = this;
     
    // Request the remote document     jQuery.ajax( type, url, params,function(res, status){
         
        if ( status == "success" || !ifModified && status == "notmodified" ) {
            // Inject the HTML into all the matched elements             self.html(res.responseText).each( callback, [res.responseText, status] );
             
            // Execute all the scripts inside of the newly-injected HTML             $("script", self).each(function(){
                if ( this.src )
                    $.getScript( this.src );
                else                     eval.call( window, this.text || this.textContent || this.innerHTML || "" );
            });
        } else             callback.apply( self, [res.responseText, status] );
    }, ifModified);
     
    return this;
};

如上代码定义了jQuery对象的ajax请求模式的load方法。load的实现里需要注意ajax请求成功以后的响应函数的实现。它会把响应内容赋值到当前jQuery对象关联的DOM元素的innerHTML属性上,并对其进行遍历调用指定的回调函数,并对新添加的脚本进行执行和获取。

标签: jquery, ajax, load
Posted by klvoek @ 2012-2-12 16:18:47 阅读(99) 评论(0)
上一篇:(十二)jQuery内置特效的实现
下一篇:js undefined 和 undeclared

我也来参与讨论

你还可以输入600/600个字符 发表评论
称呼: (必填) 登录 | 开通博客
邮箱: (选填) 你的邮箱地址不会被公开
网站: (选填)
验证码: (必填)
看不清换一张 看不清楚换一张