jQuery .ajax()html响应.查找< body> [英] jQuery .ajax() html response. Find <body>

查看:131
本文介绍了jQuery .ajax()html响应.查找< body>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.ajax调用,它通过发布请求加载URL,就像.load()一样.我正在阅读responseText以获得有效的HTML.然后,我想获取和我自己的#content ID.

I have a .ajax call which loads a url via a post request, much like .load() would do. I am reading the responseText to get the valid HTML. I would then like to grab the , and my own #content id.

标题用于替换页面标题. #content是要在页面上替换的内容,我需要class属性的body标记,因为它们是我要加载的每个页面的特定类.

The title is used to replace the title of the page. The #content is the content to replace on the page, and I need the body tag for the class attribute, as their are specific classes to each page which I would like to load.

    $.ajax({
    url: url,
    type: 'POST',
    data: {},
    complete: function (result) {

        var html = $('<div>' + result.responseText + '</div>'),
            title = html.filter('title:first').text(),
            b = html.find('body'),
            inner = html.find('#content').html();

        console.log(b);

        //change document title
        document.title = title;

        //add new content
        wrap.html(inner);

        //for home page
        $(window).trigger('resize');

        //fade in
        wrap.fadeIn(500, function () {

            wrap.trigger('newpage');
            $('#wrap').css('min-height', '100%');

        });

    }
});

假定包装被定义.请.这里的问题是,我无法出于读取类的目的而检索主体.它总是返回未定义的.我也尝试过使用.filter()而不是.find(),但是没有运气.

Assume that wrap is defined. Please. The issue here is, I cannot retrieve body for the purposes of reading the classes. It always returns undefined. I have also tried using .filter() instead of .find(), but with no luck.

有什么想法吗?

推荐答案

每个文档只能有一个<body>标签,通常浏览器会将这些标签从html中剥离.

Every document can only one <body> tag, typically browsers will strip these tags out of the html.

您只需输入以下内容即可在Chrome调试器中对其进行测试:

You can test this simply in the Chrome debugger by typing in:

$('<div><head></head><body>Example Text</body></div>');

将返回:

[<div>Example Text</div>]

JQuery API

在传递复杂的HTML时,某些浏览器可能不会生成完全复制提供的HTML源代码的DOM.如前所述,jQuery使用浏览器的.innerHTML属性来解析传递的HTML并将其插入到当前文档中.在此过程中,某些浏览器会过滤掉某些元素,例如<html><title><head>元素结果,插入的元素可能不代表所传递的原始字符串.

When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, jQuery uses the browser"s .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as <html>, <title>, or <head> elements. As a result, the elements inserted may not be representative of the original string passed.

这篇关于jQuery .ajax()html响应.查找&lt; body&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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