繁体   English   中英

为什么我不能在jQuery中解析Ajax html GET响应?

[英]Why can't I parse a Ajax html GET response in jQuery?

我正在使用Chrome扩展程序,我使用Ajax请求从请求的URL获取HTML。 这有效,但我希望得到一些特定元素的所有文本值。 例如,所有类都带有.heading-bold

的script.js

$.ajax({
        url: "http://page.com/page.html",
        type: "GET",
        dataType: "html",
          success: function(data) {
              console.log($(data).filter( '.heading_bold' ).text()); 
          }
    });

响应HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head><title>Beerpong</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <meta http-equiv="Expires" content="0" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Cache-Control" content="no-cache" />
    </head>
     <body>
        <div id="table-container">
            <table>
               <tbody>
                  <tr>
                   <td><div class="heading_bold">Beerpong</div></td>
                  </tr>
                </tbody>
            </table>
        </div>
     </body>
    </html>

将其记录到控制台工作正常。 这是我的输出:

Uncaught Error: Syntax error, unrecognized expression: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0....

为什么? 为什么不只是console.log我想要的值?

如果您使用的是jquery 1.9,请执行以下操作:

...
success: function(data) {
   var html = $.parseHTML(data); 
   console.log($(html).find( '.heading_bold' ).text()); 
}
..

因为根据jQuery 1.9 ::传递给jQuery()的HTML字符串以不同于小于字符的内容开头将被解释为选择器。 由于字符串通常不能被解释为选择器,因此最可能的结果是Sizzle选择器引擎抛出的“无效的选择器语法”错误。 使用jQuery.parseHTML()来解析任意HTML。

如果要将远程文档的一部分插入DOM,也许可以尝试使用“load”而不是“$ .get()”。

$("#result").load("page.html .heading_bold",function(response){
console.log($(this).find(".heading_bold").val());           
});

希望这对你有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM