用jQuery解析远程内容的最佳实践是什么? [英] What is the best practice for parsing remote content with jQuery?
问题描述
在执行jQuery ajax调用以检索整个XHTML文档之后,从结果字符串中选择特定元素的最佳方法是什么?也许有一个库或插件可以解决此问题?
Following a jQuery ajax call to retrieve an entire XHTML document, what is the best way to select specific elements from the resulting string? Perhaps there is a library or plugin that solves this issue?
如果在W3C规范的div中通常允许使用jQuery,则只能选择存在于字符串中的XHTML元素.因此,我很好奇要选择<title>
,<script>
和<style>
之类的东西.
jQuery can only select XHTML elements that exist in a string if they're normally allowed in a div in the W3C specification; therefore, I'm curious about selecting things like <title>
, <script>
, and <style>
.
根据jQuery文档:
According to the jQuery documentation:
HTML字符串不能包含 在一个元素内无效的元素 div,例如html,head,body或 标题元素.
The HTML string cannot contain elements that are invalid within a div, such as html, head, body, or title elements.
因此,由于我们已经确定jQuery不提供执行此操作的方法,因此我将如何选择这些元素?例如,如果您可以向我展示如何选择远程页面的标题,那将是完美的!
Therefore, since we have established that jQuery does not provide a way to do this, how would I select these elements? As an example, if you can show me how to select the remote page's title, that would be perfect!
谢谢,皮特
推荐答案
我建议您暂时退出jQuery,并使用原始XML dom方法,而不要黑客jQuery来做到这一点.使用XML Dom方法,您可以做到这一点:
Instead of hacking jQuery to do this I'd suggest you drop out of jQuery for a minute and use raw XML dom methods. Using XML Dom methods you would can do this:
window.onload = function(){
$.ajax({
type: 'GET',
url: 'text.html',
dataType: 'html',
success: function(data) {
//cross platform xml object creation from w3schools
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(data);
}
catch(e)
{
try // Firefox, Mozilla, Opera, etc.
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(data,"text/xml");
}
catch(e)
{
alert(e.message);
return;
}
}
alert(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue);
}
});
}
不要弄乱iframe等.
No messing about with iframes etc.
这篇关于用jQuery解析远程内容的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!