Trying to select a 'body' tag from html that is returned by get() request

為{幸葍}努か 提交于 2019-12-18 08:50:36

问题


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));
})

where data is contents of html file.


回答1:


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

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);
}))

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.




回答2:


jQuery uses the document object model, not the "text" that makes up that model. You only have a big piece of text in the data element that hasn't been added to the document yet.

$(body).html(data);

... assuming the data contains valid body code. It it's an entire HTML page, then you'll need to parse it for just the body content, e.g. using indexOf or somesuch.



来源:https://stackoverflow.com/questions/7839889/trying-to-select-a-body-tag-from-html-that-is-returned-by-get-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!