AJAX 生成的变成只是 firefox/chrome 中的文本内容
首先,我通过 AJAX 请求一些 HTML。
响应示例:
<tr class="recordRow">
<td class="first recordType" id="recordType">holder</td>
<td class="recordAmount" id="recordAmount">holder</td>
<td class="recordDescription" id="recordDescription">holder</td>
<td class="last recordDate" id="recordDate">holder</td>
</tr>
我正在尝试创建一个 DOM 对象。
var d = document.createElement("div");
d.innerHTML = templateListItem;
alert(d.innerHTML);
alert(d.firstChild);
我认为这应该将行添加到
中,但我只得到文本。当我将响应附加到元素时,我仅获得文本内容,例如 holderholderholderholder
。为什么 HTML 在 Firefox 和 Chrome 中似乎被压扁了?
额外: 如果示例响应如下:
<tr><td><span>something here..</span></td></tr>
它将在 Firefox 中提醒“HTMLSpanElement”。所有标签如 tr/td/ 都被删除。
First, I request some HTML via AJAX.
Example response:
<tr class="recordRow">
<td class="first recordType" id="recordType">holder</td>
<td class="recordAmount" id="recordAmount">holder</td>
<td class="recordDescription" id="recordDescription">holder</td>
<td class="last recordDate" id="recordDate">holder</td>
</tr>
And I'm trying to make a DOM Object.
var d = document.createElement("div");
d.innerHTML = templateListItem;
alert(d.innerHTML);
alert(d.firstChild);
I thought this should add the row to the <div>
, but I only get the text. When I append the response to an element, I only get the text content, e.g holder holder holder holder
.
Why does the HTML seem to get squashed in firefox and chrome?
Added:
If example response are like:
<tr><td><span>something here..</span></td></tr>
It will alert "HTMLSpanElement" in firefox. All tags like tr/td/ are removed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您尝试将
插入到
中,浏览器可能无法正确呈现它,因为它是非法 HTML。
尝试将
放入
元素或嵌套在
< 内的
元素;table>
元素。If you are trying to insert a
<tr>
into a<div>
, it is possible that the browser will not render this properly as it is illegal HTML.Try placing your
<tr>
into a<table>
element or a<tbody>
element nested inside of a<table>
element.如果您将该响应从服务器拖动到某处,那么正如您所发现的那样,它只是文本。如果可以的话,您可以更改 AJAX 代码以返回 JSON,对其进行解码,然后将其转换为对象。
关于被删除的标签,我在某处读到过有关浏览器这样做的信息,但这很可能是错误的;在这种情况下,AJAX 将会惨败。
If you're dragging that response from a server somewhere, it will just be text, as you've found out. If you can, you could change the AJAX code to return JSON, decode that, and turn it into an object.
In relation to the tags being removed, I read somewhere about browsers doing that, but it's very likely to be wrong; AJAX would fail miserably in that case.
如果您的 XHR 实例是
var xhr = new XMLHttpRequest()
,请务必使用xhr.responseXML
而不是xhr.responseText
。If your XHR instance is
var xhr = new XMLHttpRequest()
, Be sure to usexhr.responseXML
rather thanxhr.responseText
.