简体   繁体   English

如何使用 AJAX 从外部网页获取未命名元素?

[英]How to get unnamed elements from an external webpage using AJAX?

At the moment I'm trying to get an element off an external website using AJAX, so far I've (hopefully) managed to get the page:目前,我正在尝试使用 AJAX 从外部网站获取元素,到目前为止,我(希望)已经设法获取了该页面:

var xmlhttp;
var version;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    version=xmlhttp.innerHTML;
    }
  }
xmlhttp.open("GET","http://www.minecraftwiki.net/wiki/Minecraft_Wiki",true);
xmlhttp.send();

Now I just need to find a way to get the contents:现在我只需要找到一种获取内容的方法:

<dd> Current PC version: 
<b>
<a href="/wiki/Version_history#1.2.5" title="Version history">
1.2.5
</a>
</b>
</dd>

I've checked the source code of the url and sadly the element I want is unnamed (Has no id=" "), so is it still possible to do so?我已经检查了 url 的源代码,遗憾的是我想要的元素是未命名的(没有 id=" "),所以仍然可以这样做吗? And if so, how?如果是这样,怎么办? Thanks谢谢

First, you're making a cross-domain request, so unless you're using a browser that allows cross-domain AJAX, this is most likely not going to work for you without using a server-side proxy.首先,您正在发出跨域请求,因此除非您使用的浏览器允许跨域 AJAX,否则如果不使用服务器端代理,这很可能对您不起作用。

However, to answer your original question, you don't need an id attribute to access an element.但是,要回答您最初的问题,您不需要 id 属性来访问元素。 While helpful, you can access an element in any number of ways.虽然很有帮助,但您可以通过多种方式访问元素。

Class Selectors Class 选择器

var col = document.getElementsByClassName("the-class");

Then loop through the collection until you find the element you want.然后循环遍历集合,直到找到所需的元素。

jQuery Selectors: jQuery 选择器:

jQuery Selectors are perhaps the easiest way to handle DOM manipulations and get access to the element you are interested in: jQuery 选择器可能是处理 DOM 操作和访问您感兴趣的元素的最简单方法:

// example of an attribute selector:

var exampleHTML = $('div[title="example"]).html();

There is also XPath, but from my experience jQuery CSS Selectors are more modern, robust, and help speed up the development process.还有 XPath,但根据我的经验 jQuery CSS 选择器更现代、更强大,有助于加快开发过程。

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

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