如何从没有jquery的ajax responseText中获取html元素的数据

时间:2016-08-31 15:29:59

标签: javascript ajax

我想从ajax响应中获取数据,但此代码无效:

var request = new XMLHttpRequest();
request.open("GET", "http://localhost/test/test.php", true);
request.send(null);
request.onreadystatechange = function() {
    if (request.readyState == 4) {
        alert(request.responseText.document.getElementById('div1').innerHTML);
    }   
}

控制台显示以下错误:

Uncaught TypeError: Cannot read property 'getElementById' of undefined.

任何想法导致了什么?

2 个答案:

答案 0 :(得分:6)

您可以使用DOMParserhtml字符串转换为文档片段

var request = new XMLHttpRequest();
request.open("GET", "http://localhost/test/test.php", true);
request.send(null);
request.onreadystatechange = function() {
  if (request.readyState == 4) {
    var parser = new DOMParser();
    var doc = parser.parseFromString(request.responseText, "text/html");
    var elem = doc.getElementById("div1");
    alert(elem.innerHTML);
  }
}

或者,您可以将responseType设置为document

var request = new XMLHttpRequest();
request.open("GET", "file.html", true);
request.responseType = "document";
request.send(null);
request.onreadystatechange = function() {
  if (request.readyState == 4) {
    var doc = request.response;
    var elem = doc.getElementById("div1");
    alert(elem.innerHTML);
  }
}

plnkr http://plnkr.co/edit/lkpveDD31fYY1gmflK9W?p=preview

答案 1 :(得分:-1)

请求对象不是DOM元素,也不具有本机DOM所具有的方法。

使用以下代码修复代码:

#include <iostream>

void f( int, char )
{
    std::cout << "f( int, char )\n";
}

void g( double )
{
    std::cout << "g( double )\n";
}

int main( int, char*[] )
{
    auto df0 = make_fn( &f, 1, 'c' );
    auto df1 = make_fn( &g, 0.5 );
    fn_base* f0 = &df0;
    fn_base* f1 = &df1;
    f0->invoke();
    f1->invoke();
}