首页 > 解决方案 > 理解错误:未捕获的类型错误:无法在“节点”上执行“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);
}

标签: javascript

解决方案


.appendChild

[ .appendChild] 函数需要第一个参数作为Node.

以下任何一个接口都被视为Node

  1. Document
  2. Element
  3. Attr
  4. CharacterData
  5. ProcessingInstruction
  6. DocumentFragment
  7. DocumentType
  8. Notation

不属于上述任何一项的任何内容都不会被视为Node. 因此,当您传递对象或字符串 (the response) 时,会引发以下错误:

TypeError:无法在“Node”上执行“appendChild”:参数 1 不是“Node”类型。

ajax 请求返回的response很可能是一个Object.

JSON.stringify将转换ObjectString.

两者都不是列出的接口之一。


推荐阅读