javascript 为什么我不能在 jQuery 中解析 Ajax html GET 响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21038544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can't I parse a Ajax html GET response in jQuery?
提问by Hyman
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
我正在调整 Chrome 扩展程序,在该扩展程序中我使用 Ajax 请求从请求的 URL 获取 HTML。这有效,但我想获得某些元素的所有文本值。例如,类script.js 的所有内容.heading-bold
$.ajax({
url: "http://page.com/page.html",
type: "GET",
dataType: "html",
success: function(data) {
console.log($(data).filter( '.heading_bold' ).text());
}
});
Response HTML
响应 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....
Why? Why won't it just console.log my desired values?
为什么?为什么它不只是 console.log 我想要的值?
回答by Sudhir Bastakoti
If you are using jquery 1.9, do:
如果您使用的是 jquery 1.9,请执行以下操作:
...
success: function(data) {
var html = $.parseHTML(data);
console.log($(html).find( '.heading_bold' ).text());
}
..
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 1.9:: 传递给 jQuery() 的以小于号以外的字符开头的 HTML 字符串将被解释为选择器。由于该字符串通常不能被解释为选择器,因此最有可能的结果将是 Sizzle 选择器引擎抛出的“无效选择器语法”错误。使用 jQuery.parseHTML() 解析任意 HTML。
回答by Chickenrice
Maybe you could try to use "load" instead of "$.get()" if you want to insert a portion of the remote document into DOM.
如果您想将远程文档的一部分插入到 DOM 中,也许您可以尝试使用“load”而不是“$.get()”。
$("#result").load("page.html .heading_bold",function(response){
console.log($(this).find(".heading_bold").val());
});
Hope this is helpful to you.
希望这对你有帮助。