javascript - 理解错误:未捕获的类型错误:无法在“节点”上执行“appendChild”:参数 1 不是“节点”类型
问题描述
我已经看到了一些与此错误有关的问题,而我的解决方案有所不同。也许有人可以解释这一点?我知道我需要将 JSON 响应转换为字符串,但在这方面,错误消息对我来说毫无意义。
var root = "someurl";
url = root + url;
$.ajax({
type: 'POST',
url: url,
data: formData,
}).done(function (response) {
// Fails with error: Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
document.getElementById("resultBox").appendChild(response);
// OK
document.getElementById("resultBox").textContent = JSON.stringify(response, null, 4);
}
解决方案
.appendChild
[ .appendChild
] 函数需要第一个参数作为Node
.
以下任何一个接口都被视为Node
:
不属于上述任何一项的任何内容都不会被视为Node
. 因此,当您传递对象或字符串 (the response
) 时,会引发以下错误:
TypeError:无法在“Node”上执行“appendChild”:参数 1 不是“Node”类型。
ajax 请求返回的response
很可能是一个Object
.
JSON.stringify
将转换Object
为String
.
两者都不是列出的接口之一。
推荐阅读
- css - Capybara:匹配具有特定属性但没有任何值的 CSS(例如,匹配,但既不匹配也不匹配)
- ionic-framework - 请在注销 ionic 5 之前使用 login 或 trySilentLogin
- ios - AWS Amplify - 同步数据存储
- selenium-webdriver - 使用 Jmeter 中的 Selenium Webdriver 从元素内部按标签获取元素
- here-api - 我使用 HERE api 收到地理围栏请求错误
- firebase - 使用 Firestore Cloud Function 将所有记录导出到 Algolia 索引
- php - Symfony 序列化器组件:你能优先使用 has 方法而不是 get 吗?
- spring-boot - 运行 maven 应用程序时出现错误
- mysql - MySQL - 无法添加或更新子行
- r - 如何在 R 中的热图中为行和列设置 Times New Roman 文本