首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在ajax HTML响应中查找body标记

在ajax HTML响应中查找body标记
EN

Stack Overflow用户
提问于 2013-01-20 17:34:22
回答 2查看 27.7K关注 0票数 23

我正在进行一个ajax调用来获取内容,并像这样追加这个内容:

代码语言:javascript
复制
$(function(){
    var site = $('input').val();
    $.get('file.php', { site:site }, function(data){
        mas = $(data).find('a');
        mas.map(function(elem, index) {
            divs = $(this).html();
            $('#result').append('' + divs + '');
        })
    }, 'html');
});

问题是,当我在body中更改a时,我什么也得不到(没有错误,没有html)。我假设body是一个标签,就像'a‘是?我做错了什么?

所以这对我来说很有效:

代码语言:javascript
复制
 mas = $(data).find('a');

但这不是:

代码语言:javascript
复制
 mas = $(data).find('body');
EN

回答 2

Stack Overflow用户

发布于 2013-01-20 18:00:53

我做了一些实验,并在一定程度上找出了原因,所以在等待我感兴趣的真正答案之前,这里有一个技巧来帮助理解这个问题。

代码语言:javascript
复制
$.get('/',function(d){
    // replace the `HTML` tags with `NOTHTML` tags
    // and the `BODY` tags with `NOTBODY` tags
    d = d.replace(/(<\/?)html( .+?)?>/gi,'$1NOTHTML$2>',d)
    d = d.replace(/(<\/?)body( .+?)?>/gi,'$1NOTBODY$2>',d)
    // select the `notbody` tag and log for testing
    console.log($(d).find('notbody').html())
})

编辑:进一步的实验

如果你把内容加载到一个iframe中,然后你可以通过某个dom对象层次结构来访问框架内容,这似乎是可能的……

代码语言:javascript
复制
// get a page using AJAX
$.get('/',function(d){

    // create a temporary `iframe`, make it hidden, and attach to the DOM
    var frame = $('<iframe id="frame" src="/" style="display: none;"></iframe>').appendTo('body')

    // check that the frame has loaded content
    $(frame).load(function(){

        // grab the HTML from the body, using the raw DOM node (frame[0])
        // and more specifically, it's `contentDocument` property
        var html = $('body',frame[0].contentDocument).html()

        // check the HTML
        console.log(html)

        // remove the temporary iframe
        $("#frame").remove()

    })
})

编辑:更多研究

似乎contentDocument是获取iFrame的window.document元素的符合标准的方法,但IE当然并不真正关心标准,所以这就是如何以跨平台的方式获得对iFrame的window.document.body对象的引用……

代码语言:javascript
复制
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
var iframeBody = iframeDoc.body;
// or for extra caution, to support even more obsolete browsers
// var iframeBody = iframeDoc.getElementsByTagName("body")[0]

请参阅:contentDocument for an iframe

票数 6
EN

Stack Overflow用户

发布于 2019-08-11 20:00:37

为我工作的Regex解决方案:

代码语言:javascript
复制
var head = res.match(/<head.*?>.*?<\/head.*?>/s);
var body = res.match(/<body.*?>.*?<\/body.*?>/s);

详细说明:https://regex101.com/r/kFkNeI/1

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14423257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档