为什么我不能在jQuery中解析Ajax html GET响应? [英] Why can't I parse a Ajax html GET response in jQuery?

查看:112
本文介绍了为什么我不能在jQuery中解析Ajax html GET响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


script.js

I'm tempering with a Chrome Extension where I use an Ajax-request to get HTML from a requested URL. This works, but I want to get all the text values some certain elements. By example, everything with the class .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>

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

Logging it to the console works just fine. This is my output:

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

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

Why? Why won't it just console.log my desired values?

推荐答案

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

If you are using jquery 1.9, do:

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

因为根据 jQuery 1.9 :: HTML字符串传递给jQuery()启动除了小于字符之外的东西将被解释为选择器。由于字符串通常不能被解释为选择器,最可能的结果将是Sizzle选择器引擎抛出的无效的选择器语法错误。使用jQuery。 parseHTML()解析任意HTML。

Because as per jQuery 1.9:: HTML strings passed to jQuery() that start with something other than a less-than character will be interpreted as a selector. Since the string usually cannot be interpreted as a selector, the most likely result will be an "invalid selector syntax" error thrown by the Sizzle selector engine. Use jQuery.parseHTML() to parse arbitrary HTML.

这篇关于为什么我不能在jQuery中解析Ajax html GET响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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