我想从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.
任何想法导致了什么?
答案 0 :(得分:6)
您可以使用DOMParser
将html
字符串转换为文档片段
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);
}
}
答案 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();
}