码迷,mamicode.com
首页 > Web开发 > 详细

jQuery源码中的Ajax--load方法

时间:2016-07-19 22:02:40      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

  load()方法是jQuery中最为简单和常用的方法,能载入远程HTML代码幷插入到DOM中,其结构为:

load(url [.data] [.callback])

  各参数解释如下:

参数名称 类型 说明
url String 请求HTML页面的URL地址
data(可选) Object 发送至服务器的key/value数据
callback(可选) Function 请求完成时的回调函数,无论请求成功或失败

  load的源码如下:(源码目录:jquery/src/ajax/load.js

define( [
    "../core",
    "../core/parseHTML",
    "../ajax",
    "../traversing",
    "../manipulation",
    "../selector"
], function( jQuery ) {

"use strict";

/**
 * Load a url into a page
 */
jQuery.fn.load = function( url, params, callback ) {
    var selector, type, response,
        self = this,
        off = url.indexOf( " " );

    if ( off > -1 ) {
        selector = jQuery.trim( url.slice( off ) );
        url = url.slice( 0, off );
    }

    // If it‘s a function
    if ( jQuery.isFunction( params ) ) {

        // We assume that it‘s the callback
        callback = params;
        params = undefined;

    // Otherwise, build a param string
    } else if ( params && typeof params === "object" ) {
        type = "POST";
    }

    // If we have elements to modify, make the request
    if ( self.length > 0 ) {
        jQuery.ajax( {
            url: url,

            // If "type" variable is undefined, then "GET" method will be used.
            // Make value of this field explicit since
            // user can override it through ajaxSetup method
            type: type || "GET",
            dataType: "html",
            data: params
        } ).done( function( responseText ) {

            // Save response for use in complete callback
            response = arguments;

            self.html( selector ?

                // If a selector was specified, locate the right elements in a dummy div
                // Exclude scripts to avoid IE ‘Permission Denied‘ errors
                jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :

                // Otherwise use the full result
                responseText );

        // If the request succeeds, this function gets "data", "status", "jqXHR"
        // but they are ignored because response was set above.
        // If it fails, this function gets "jqXHR", "status", "error"
        } ).always( callback && function( jqXHR, status ) {
            self.each( function() {
                callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
            } );
        } );
    }

    return this;
};

} );

  整个源码的工作如下:

jQuery源码中的Ajax--load方法

标签:

原文地址:http://www.cnblogs.com/niulina/p/5686327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!