理解错误:未捕获的TypeError:无法在“节点”上执行“ appendChild”:参数1的类型不是“节点”

时间:2019-05-08 04:06:14

标签: javascript

我已经看到了与此错误有关的几个问题,而我的解决方案则有所不同。也许有人可以解释一下?我知道我需要将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);
}

1 个答案:

答案 0 :(得分:1)

.appendChild

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

以下任一界面都被视为Node

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

任何不符合上述条件之一的内容均不视为Node。因此,当您传递对象或字符串(response)时,会出现以下错误:

  

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

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

JSON.stringify会将Object转换为String

两者都不是列出的界面之一。