xmlhttpRequest获取xml

xmlhttpRequest获取xml

本文介绍了用GM_xmlhttpRequest获取xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用greasemonkey检索一个页面,然后从中提取一个链接,将该链接插入到当前页面中。我有麻烦:

I'm trying to retrieve a page with greasemonkey and then extract a link from it, inserting the link into the current page. I'm having some trouble with:

GM_xmlhttpRequest({
method: "GET",
url: "http://www.test.net/search.php?file=test",

onload: function(data)
{
    if (!data.responseXML)
    {
        data.responseXML = new DOMParser().parseFromString(data.responseText, "text/xml");
    }
    alert("!");
    var xmldata = data.response.xml;
    var tests = xmldata.getElementsByTagName('test');
    alert(tests[0].innerHTML);
}

});

该页面有效,当我尝试以前,GM_xmlhttpRequest作为字符串正确返回,但我可以似乎弄清楚如何做到这一点,所以我可以使用节点操作。提前提醒。

The page is valid, and GM_xmlhttpRequest returned it correctly as a string when I tried previously, but I can't seem to figure out how to make it so I can use node operations on it.Thanks in advance.

编辑 - 第二个相关问题strong>

Edit - a second, related question

我应该如何引用当前页面,以便我可以将其传递给函数,就像我将通过我的页面一样? Ex

How should I refer to the current page so that I could pass it a to function, just as I would pass my fetched page? Ex

function FindTests(currentpage)
{
    currentpage.getElementById('blah');
}

最初我传递它的文档,但后来我使用获取的页面。对不起,如果措辞令人困惑。

where initially I pass it document, but later I use the fetched page. Sorry if the wording is confusing.

推荐答案

如果请求的页面是一个格式良好的xml,那么你是正确的方式。

,但您应该将 data.response.xml 更改为 data.responseXML

if the requested page is a well-formatted xml, then you are in the correct way.
but you should change data.response.xml to data.responseXML

而且我认为你不能用 XMLDocument (xml解析器的结果)这样做,因为 .getElementById HTMLDocument 中工作。

但是,您可以执行以下操作来获取有效的HTMLDocument: / p>

and i THINK you can't do this with a XMLDocument (result of the xml parser) because .getElementById works in HTMLDocument.
however, you could do the following to have a valid HTMLDocument:

if (/^Content-Type: text\/xml/m.test(data.responseHeaders)) {
    data.responseXML = new DOMParser().parseFromString(data.responseText, "text/xml");
}
else if (/^Content-Type: text\/html/m.test(data.responseHeaders)) {
    var dt = document.implementation.createDocumentType("html", "-//W3C//DTD HTML 4.01 Transitional//EN", "http://www.w3.org/TR/html4/loose.dtd");
    var doc = document.implementation.createDocument(null, null, dt);

    // I have to find a workaround because this technique makes the html*/head/body tags to disappear.
    var html = document.createElement('html');
    html.innerHTML = data.responseText;
    doc.appendChild(html);

    data.responseXML = doc;
}

来源:

这篇关于用GM_xmlhttpRequest获取xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 13:06