如何使用javascript从另一个页面(同一个域)的内容中获取信息? [英] How to use javascript to get information from the content of another page (same domain)?
问题描述
假设我有一个网页( /index.html
),其中包含以下内容
Let's say I have a web page (/index.html
) that contains the following
<li>
<div>item1</div>
<a href="/details/item1.html">details</a>
</li>
我希望在 /index.html上有一些javascript
加载
/details/item1.html
页面并从该页面中提取一些信息。
页面 /details/item1.html
可能包含以下内容:
and I would like to have some javascript on /index.html
to load that
/details/item1.html
page and extract some information from that page.
The page /details/item1.html
might contain things like
<div id="some_id">
<a href="/images/item1_picture.png">picture</a>
<a href="/images/item1_map.png">map</a>
</div>
我的任务是写一个greasemonkey脚本,所以更改任何服务器都不是一个选项。
My task is to write a greasemonkey script, so changing anything serverside is not an option.
总结一下,javascript正在 /index.html
上运行,我想
喜欢将javascript代码添加到添加从 /index.html
和<$ c $中提取的 /index.html
的一些信息C> /details/item1.html 。
我的问题是如何从 /details/item1.html
获取信息。
To summarize, javascript is running on /index.html
and I would
like to have the javascript code to add some information on /index.html
extracted from both /index.html
and /details/item1.html
.
My question is how to fetch information from /details/item1.html
.
我目前有用于提取链接的编写代码(例如 /details/item1.html
)
并将其传递给应提取所需信息的方法(首先是$ b来自some_id div的$ b只是.innerHTML是好的,我可以稍后处理。)
I currently have written code to extract the link (e.g. /details/item1.html
)
and pass this on to a method that should extract the wanted information (at first
just .innerHTML from the some_id div is ok, I can process futher later).
以下是我目前的尝试,但它不起作用。有什么建议吗?
The following is my current attempt, but it does not work. Any suggestions?
function get_information(link)
{
var obj = document.createElement('object');
obj.data = link;
document.getElementsByTagName('body')[0].appendChild(obj)
var some_id = document.getElementById('some_id');
if (! some_id) {
alert("some_id == NULL");
return "";
}
return some_id.innerHTML;
}
推荐答案
首先:
function get_information(link, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", link, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.responseText);
}
};
xhr.send(null);
}
然后
get_information("/details/item1.html", function(text) {
var div = document.createElement("div");
div.innerHTML = text;
// Do something with the div here, like inserting it into the page
});
我还没有测试过这一点 - 我的头脑。 YMMV
I have not tested any of this - off the top of my head. YMMV
这篇关于如何使用javascript从另一个页面(同一个域)的内容中获取信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!