javascript - 在使用Ajax加载外部文件,为什么在提示之后才加载完成?
PHP中文网
PHP中文网 2017-04-11 13:05:53
[JavaScript讨论组]

使用js来加载外部文件,但是在提示之后才会加载文件,而不是在加载之后显示加载成功。为什么呢?




    
    Title
    
    


    

PHP中文网
PHP中文网

认证0级讲师

全部回复(3)
黄舟

原因是jQuery load方法的实现是先填充DOM再调用回调函数。

下面是jQuery load方法的源码:

jQuery.fn.load = function( url, params, callback ) {
    if ( typeof url !== "string" && _load ) {
        return _load.apply( this, arguments );
    }

    var selector, response, type,
        self = this,
        off = url.indexOf(" ");

    if ( off >= 0 ) {
        selector = url.slice( off, url.length );
        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
            type: type,
            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 p
                // Exclude scripts to avoid IE 'Permission Denied' errors
                jQuery("<p>").append( jQuery.parseHTML( responseText ) ).find( selector ) :

                // Otherwise use the full result
                responseText );

        }).complete( callback && function( jqXHR, status ) {
            self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
        });
    }

    return this;
};

你传入的文件路径text/text最终仍然是通过ajax去获取的,获取了文件内容后,在done方法里使用.html()把内容放到了DOM元素中,然后调用complete函数,而传入参数中的回调函数callback是在complete函数中调用的。

所以,是先调用的self.html(data),渲染好了DOM,然后再调用回调函数。

怪我咯

text没有后缀名?

天蓬老师

文件路径

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号