jQuery解析AJAX返回的html数据时碰到的问题与解决

今天做项目的时候,碰到一个问题。具体情况是,我需要使用AJAX动态的获取某个HTML页面的内容(注意,获取的不是HTML片(snip),而是真正的页面,有<html>, </html>的这种。我想的很简单,获得之后,用jQuery解析一下,取出我要的部分,然后放到页面的某个元素里面。但是,实际情况是,jQuery怎么也解析不了返回的HTML页面。代码如下:


$(document).ready(function () {
    jQuery.ajax({
        url: "http://localhost/topCrashCommands?productId=AutoCAD 2014",
        type: "GET",
        success: function (data) {
            var table = $(".ui-layout-center", $(data));
            $("#data").html(table.html());
        },
        dataType: "html"
    });
});

最后,花了将近2个小时才解决,原因就是,我应该把返回的html用一个标签来包装一下,代码如下:

            jQuery.ajax({
                url: "http://localhost/topCrashCommands?productId=AutoCAD 2014",
                type: "GET",
                success: function (data) {
                    var wrappedObj = $("<code></code>").append($(data));
                    var table = $(".ui-layout-center", wrappedObj);
                    $("#data").html(table.html());

                },
                dataType: "html"
            });

具体为什么要包一下,我不太清楚,很有可能是因为html里面包含的html, title, body等标记被强制的移除掉了,导致我的html不是一个合法的DOM树了,就是说根节点不止1个了。为什么html, title, body这些标记会被强制移除了,jQuery的文档有写,假如传入的html片很复杂,即超过一个标记且包含属性,那个jQuery会调用浏览器的innerHTML来创建DOM树,而浏览器通常会把那些标记移除掉。


OK,就写这么多了。完整的HTML如下:

<!DOCTYPE html>
<html>
<head>
    <% include header_title_meta %>
    <% include header_jquery %>
    <% include header_util %>
    <% include header_jquery_ui %>
    <% include header_layout %>
    <% include header_css %>

    <% include header_underscore %>

    <script>
        $(document).ready(function () {
            //jQuery.ajax({
            //    url: "http://localhost/weeklyCrashCount?productId=AutoCAD 2014",
            //    type: "GET",
            //    success: function (data) {
            //        var wrappedObj = $("<code></code>").append($(data));
            //        var chart = $(".ui-layout-center", wrappedObj);
            //        $("#data").html(chart.html());

            //    },
            //    dataType: "html"
            //});
            jQuery.ajax({
                url: "http://localhost/topCrashCommands?productId=AutoCAD 2014",
                type: "GET",
                success: function (data) {
                    var wrappedObj = $("<code></code>").append($(data));
                    var table = $(".ui-layout-center", wrappedObj);
                    $("#data").html(table.html());

                },
                dataType: "html"
            });
        });
    </script>

</head>
<body>
    <% include fragment_header %>
    <% include fragment_links %>
    <div id="data" class="ui-layout-center">
    </div>
</body>
</html>






原文地址:https://www.cnblogs.com/puncha/p/3876916.html