我正在通过AJAX调用获取HTML代码,然后将代码附加到现有的HTML元素。
问题是,附加的代码包含逃逸的字符,导致HTML破坏,并导致偶然的元素看起来像这样:与我们联系我们▸ \ n
:
\ n“>
html元素是:< li class =“ listItems”>< a href =“ \/contact“ class =” listLinks“>与我们联系我们
▸参考,接收到的AJAX响应是:
"<li class='listitems'><a href='https:\/\/website.com\/contact' class='listlinks'>Contact Us ▸<\/a><\/li>\n"
和用于将其添加到现有 ul
元素的JavaScript代码是:
let r = httpRequest.responseText; // The AJAX response
document.getElementById('mylist').insertAdjacentHTML("beforeend",r);
我也尝试使用以下内容:
let r = httpRequest.responseText; // The AJAX response
document.getElementById('mylist').interHTML += r;
但是AM在观察相同的结果。
但是,当我在浏览器的控制台中尝试JavaScript代码时:我会得到预期的结果:与我们联系▸ 联系我们▸
“ nofollow noreferrer”>
“ listItems”&gt;&lt; a href = “ 为什么该代码不会被静止不动和评估为HTML,但是当我使用浏览器的控制台窗口手动进行操作时,它起作用。
谁能告诉我我在这里缺少什么以及如何解决这个问题?
I am fetching HTML code via an AJAX call, and then appending the code it to an existing HTML element.
Problem is, the appended code contains escaped characters, causing the HTML to break, and resulting in haphazard elements looking like this: Contact Us ▸<\/a><\/li>\n
:

The HTML element is: <li class="listitems"><a href="https:\/\/website.com\/contact" class="listlinks">Contact Us ▸<\/a><\/li>\n</a></li>
For reference, the ajax response received is:
"<li class='listitems'><a href='https:\/\/website.com\/contact' class='listlinks'>Contact Us ▸<\/a><\/li>\n"
And the JavaScript code used to add this to the existing ul
element is:
let r = httpRequest.responseText; // The AJAX response
document.getElementById('mylist').insertAdjacentHTML("beforeend",r);
I've also tried using the following:
let r = httpRequest.responseText; // The AJAX response
document.getElementById('mylist').interHTML += r;
but am observing the same results.
However, when I try either JavaScript code in the browser's console: I get the expected results: Contact Us ▸
And the HTML element is: <li class="listitems"><a href="https://website.com/contact" class="listlinks">Contact Us ▸</a></li>
I am unable to understand why the code is not being unescaped and evaluated as HTML normally, but it works when I do it manually using the browser's console window.
Can anyone tell me what I'm missing here and how I can fix this?
发布评论
评论(1)
响应是JSON,您需要对其进行解析。
The response is JSON, you need to parse it.