【问题标题】:"getElementById not a function" when trying to parse an AJAX response?尝试解析 AJAX 响应时“getElementById 不是函数”?
【发布时间】:2012-11-20 04:56:16
【问题描述】:

我正在运行 GM_xmlhttpRequest(在 Greasemonkey 脚本中)并将 responseText 存储到新创建的 HTML 元素中:

var responseHTML = document.createElement('HTML');
...
onload: function() { responseHTML.innerHTML = response.responseText; }


然后我试图在responseHTML 中找到一个元素:

console.log(responseHTML.getElementsByTagName('div'));
console.log(responseHTML.getElementById('result_0'));


第一个工作正常,但不是第二个。有什么想法吗?

【问题讨论】:

    标签: javascript xmlhttprequest greasemonkey getelementbyid gm-xmlhttprequest


    【解决方案1】:

    使用DOMParser()responseText 转换为可搜索的DOM 树。
    此外,您尝试搜索/使用派生自 responseText 的任何内容都必须发生在 onload 函数内。

    使用这样的代码:

    GM_xmlhttpRequest ( {
        ...
        onload:     parseAJAX_ResponseHTML,
        ...
    } );
    
    function parseAJAX_ResponseHTML (respObject) {
        var parser      = new DOMParser ();
        var responseDoc = parser.parseFromString (respObject.responseText, "text/html");
    
        console.log (responseDoc.getElementsByTagName('div'));
        console.log (responseDoc.getElementById('result_0'));
    }
    


    当然,还要验证一个 id result_0 的节点实际上是否在返回的 HTML 中。 (使用 Firebug、Wireshark 等)

    【讨论】:

    • 他的代码和你的代码工作方式一样:意味着你的代码因为同样的原因不能工作 - getElementById 不是 HTML 元素的方法,它是文档的方法。
    • @slebetman:不,我的代码确实有效,responseDoc 一个文档。 ...您可以看到它在fiddle.jshell.net/UEuKZ/show 有效。 (代码是仅限Firefox,这没关系,因为这是Greasemonkey 问题)。
    • 啊,错过了greasemonkey标签。对不起。
    • 谢谢,伙计们。我倾向于避开 DOMParser,因为过去我无法让它工作 ^_^ 但无论如何,我明白为什么它现在不能工作了。
    【解决方案2】:

    getElementById 不是 HTML 元素的方法。它是文档节点的一种方法。因此你不能这样做:

    div.getElementById('foo'); // invalid code
    

    您可以通过递归遍历children 来实现自己的函数来搜索DOM。在较新的浏览器上,您甚至可以使用querySelector 方法。对于最小的开发,您可以使用 jQuery 或 sizzle.js(jQuery 背后的查询引擎)等库。

    【讨论】:

      【解决方案3】:

      不需要将响应存储在元素中,也不需要使用 DOMParser()

      只需将responseType设置为'document',响应将被自动解析并存储在responseXML中

      例子:

      var ajax = new XMLHttpRequest();
      ajax.open('get','http://www.taringa.net');
      ajax.responseType = 'document';
      ajax.onload = function(){
          console.log(ajax.responseXML); //And this is a document which may execute getElementById
      };
      ajax.send();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-21
        • 2017-05-04
        • 1970-01-01
        • 2014-07-07
        • 2018-11-22
        • 2016-05-05
        相关资源
        最近更新 更多