javascript - 在使用Ajax加载外部文件,为什么在提示之后才加载完成?

查看:81
本文介绍了javascript - 在使用Ajax加载外部文件,为什么在提示之后才加载完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function(){
                $("#div1").load("text/text",function (responseTxt,statusTxt,xhr) {
                        if (statusTxt=="success")
                            alert("加载成功!");
                        if(statusTxt=="error")
                            alert("加载失败:"+xhr.status+" "+xhr.statusText);
                });
            });
        });
    </script>
</head>
<body>
    <div id="div1"></div>
    <button id="btn">点击加载外部文件</button>
</body>

解决方案

原因是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 div
                // Exclude scripts to avoid IE 'Permission Denied' errors
                jQuery("<div>").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,然后再调用回调函数。

这篇关于javascript - 在使用Ajax加载外部文件,为什么在提示之后才加载完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆