如何使用javascript从另一个页面(同一个域)的内容中获取信息?

hlo*_*dal 1 javascript

假设我有一个/index.html包含以下内容的网页()

<li>
    <div>item1</div>
    <a href="/details/item1.html">details</a>
</li>
Run Code Online (Sandbox Code Playgroud)

我想要一些javascript /index.html来加载该 /details/item1.html页面并从该页面中提取一些信息.该页面/details/item1.html可能包含类似的内容

<div id="some_id">
    <a href="/images/item1_picture.png">picture</a>
    <a href="/images/item1_map.png">map</a>
</div>
Run Code Online (Sandbox Code Playgroud)

我的任务是编写一个greasemonkey脚本,因此不能选择更改任何服务器端.

总之,JavaScript的运行上/index.html,我想有JavaScript代码中添加一些信息/index.html 来自提取/index.html/details/item1.html.我的问题是如何从中获取信息/details/item1.html.

我目前已经编写了代码来提取链接(例如/details/item1.html)并将其传递给一个应该提取所需信息的方法(起初只是.someHT文件中的.innerHTML是好的,我可以稍后再处理).

以下是我目前的尝试,但它不起作用.有什么建议?

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;
}
Run Code Online (Sandbox Code Playgroud)

jim*_*mbo 6

第一:

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);
}
Run Code Online (Sandbox Code Playgroud)

然后

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
});
Run Code Online (Sandbox Code Playgroud)

我没有测试任何这个 - 从我的头顶.因人而异