首页 文章

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

提问于
浏览
4

我正在使用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()); 
          }
    });

Response 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我想要的值?

2 回答

  • 16

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

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

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

  • 1

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

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

    希望这对你有所帮助 .

相关问题