尝试从get()请求返回的html中选择一个"body"标签 [英] Trying to select a 'body' tag from html that is returned by get() request

查看:224
本文介绍了尝试从get()请求返回的html中选择一个"body"标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行 ajax get调用,该操作返回了html页面的内容.我正在尝试选择body标记的内容,但是我的选择器返回了一个空的jquery对象.

I'm making an ajax get call that returns me contents of html page. I'm trying to select contents of the body tag but my selector returns an empty jquery object.

$.get(filename, function(data) {
    console.log($("body", data));
})

其中data是html文件的内容.

where data is contents of html file.

推荐答案

jQuery无法选择响应字符串的body,因为当使用$()转换字符串时,<body>标签会消失.

jQuery cannot select body of the response string, because the <body> tag disappears when the string is converted using $().

因此,您必须以其他方式从data字符串中选择主体,例如正则表达式.示例:

Hence, you have to select the body from the data string in another way, such as Regular expressions. Example:

$.get(filename, function(data) {
    var body = data.replace(/^[\S\s]*<body[^>]*?>/i, "")
                    .replace(/<\/body[\S\s]*$/i, "");
    //Optionally, convert the string to a jQuery object:
    body = $(body);
    console.log(body);
}))

注意:我的正则表达式假定格式正确的HTML文档,其中>是使用HTML实体正确显示的.如果不是这种情况,则必须使用更高级的RegExp,例如

Note: My Regular Expression assumed a wellformed HTML document, where > are correctly shown using HTML entities. If this is not the case, more advanced RegExps has to be used, such as the ones shown at this question.

这篇关于尝试从get()请求返回的html中选择一个"body"标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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