为什么jQuery无法找到并返回所有HTML标签,即body/title


why cant jquery find and return all html tags i.e. body/title

我在这方面花了很长时间,不明白为什么它不起作用。我正在使用ajax向php curl发送一个帖子,该帖子在其中带来了一个url,然后返回到ajax。 当我发送警报时,该页面的所有html都显示在警报中。 现在我想使用 jquery 来查找每个元素,即 body、h1、title 并输出内容,但当我这样做时,它不适用于正文或标题。 为什么?

这是我的查询

        $.ajax({
      type: "POST",
      url: "senddom.php",
      data: {"dataString" : dataString },
      success: function(response) {   
  $('body').append("<p> contents of title:" + $(this).find('title').html() + "</p>");       
  $('body').append("<p> contents of all: " + $(this).find('body').html() + "</p>");
 $(response).find('h1').each(function() {
  $('body').append("<p> contents of H1: " + $(this).text() + "</p>");
});

这是我的PHP

<?php 
    $site= $_POST['dataString'];             // get data
function curl_get($site){
    $useragent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$site);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    $data=curl_exec($ch);
    curl_close($ch);
    return $data;

}
function getdom($site){
    $html = curl_get($site);
    $xml = new DOMDocument();
    @$xml->loadHTML($html);
    echo($html);

}
echo getdom($site);
?>
在你的

成功块中:$(this) -> $(response)

跟进:全文 HTML 与片段

虽然这似乎可以解决眼前的问题,但它取决于您的响应是否是完整的正文 HTML。

在这种情况下,似乎response全文 HTML。

jQuery parseHTML 方法不处理全文 HTML,不幸的是response不会被正确解析。更多信息请参阅:https://github.com/jquery/jquery/blob/master/src/core.js

如果您希望解析全文 HTML,一种方法是使用 DOMParser API。值得注意的是,目前缺乏对解析"text/html"的支持;仅在火狐中可用。另一种选择是document.implementation除IE<9之外的所有支持。

也就是说,在你想使用DOMParser的情况下举个例子——

parser = new DOMParser();
doc = parser.parseFromString(response, "text/html");
$response = $(doc)
$response.find('title').text()
您想

使用documentation.implementation的示例 --

var doc = document.implementation.createHTMLDocument("");
var doc_el = doc.documentElement;
doc_el.innerHTML = response;
$response = $(doc_el); // 
$response.find('title').text()

有关更多信息,我将遵循我在github上找到的一个不错的jQuery插件(处理x浏览器支持):jquery.parsehtml.js。