gpt4 book ai didi

javascript - 如何在没有jquery的情况下从ajax responseText中获取html元素的数据

转载 作者:行者123 更新时间:2023-11-28 13:15:02 24 4
gpt4 key购买 nike

我想从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.

你知道是什么原因造成的吗?

最佳答案

您可以使用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

关于javascript - 如何在没有jquery的情况下从ajax responseText中获取html元素的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39253618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com