简体   繁体   English

在jQuery中解析HTML响应

[英]Parsing HTML Response in jQuery

My page needs to grab a specific div from another page to display within a div on the current page. 我的页面需要从另一个页面抓取一个特定的div才能在当前页面的div中显示。 It's a perfect job for $.load , except that the HTML source I'm pulling from is not necessarily well-formed, and seems to have occasional tag errors, and IE just plain won't use it in that case. 对于$.load ,这是一项完美的工作,除了我从中获取的HTML源代码不一定格式正确,并且似乎偶尔会出现标签错误,IE在这种情况下也不会使用它。 So I've changed it to a $.get to grab the HTML source of the page as a string. 因此,我将其更改为$.get来获取页面的HTML源字符串。 Passing it to $ to parse it as a DOM has the same problem in IE as $.load , so I can't do that. 将其传递给$以将其解析为DOM在IE中与$.load有着相同的问题,所以我不能这样做。 I need a way to parse the HTML string to find the contents of my div#information , but not the rest of the page after its </div> . 我需要一种解析HTML字符串的方法来查找div#information的内容,而不是页面</div>之后的其余部分。 (PS My div#information contains various other div 's and elements.) (PS My div#information包含其他各种div和元素。)

EDIT: Also if anyone has a fix for jQuery's $.load not being able to parse response HTML in IE, I'd love to hear that too. 编辑:另外,如果有人修复了jQuery的$.load而不能够解析IE中的响应HTML,我也很想听听。

If the resource you are trying to load is under your control, your implementation spec is poorly optimized. 如果您要加载的资源在您的控制之下,则实现规范的优化很差。 You don't want to ask your server for an entire page of content when you only really need a small piece of that content. 当您只真正需要一小部分内容时,您不想向服务器询问整个内容。

What you'll want to do is isolate the content you want, and have the server return only what you need. 您要做的就是隔离所需的内容,并使服务器仅返回您需要的内容。

As a side note, since you are aware that you have malformed HTML, you should probably bite the bullet and validate your markup. 附带说明一下,由于您知道HTML格式错误,因此您可能应该硬着头皮并验证您的标记。 That will save you some trouble (like this) in the future. 这样可以为您将来省去一些麻烦(像这样)。

Finally, if you truly cannot optimize this process, my guess is that you are creating an inconsistency because some element in the parsed HTML has the same ID as an element on your current page. 最后,如果您确实无法优化此过程,那么我猜您正在创建一个不一致的地方,因为所解析的HTML中的某些元素具有与当前页面上的元素相同的ID。 Identical ID's are invalid and lead to many cross-browser JavaScript problems. 相同的ID无效,并导致许多跨浏览器的JavaScript问题。

Strictly with strings you could use a regular expression to find the id="information" tag contents. 严格使用字符串,您可以使用正则表达式查找id="information"标签内容。 Never parse it as html. 永远不要将其解析为html。

I'd try the $.load parameter that accepts a html selector as well 我会尝试$.load参数也接受html选择器

$('#results').load('/MySite/Url #Information');

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

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