jQuery源碼中的Ajax--load方法

來源:互聯網
上載者:User

標籤:

  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方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.