【问题标题】:Output a comment in an XML file from ajax call通过 ajax 调用在 XML 文件中输出注释
【发布时间】:2018-10-21 06:01:43
【问题描述】:

如何将 .xml 文件中的注释内容输出到我的文本区域?

我的 .html:

<textarea name="comment" id="comment" rows="3"/>

我的 .xml:

<div>
<ab type="transcription"><!--This is a comment--></ab>
</div>

我的 .js:

$.ajax({
type: "GET",
url: "../data/cards/1799.xml",
dataType: "xml",
cache: false,
success: function (xml) {
[...]
var mycomment = $(xml).find("ab").attr("type", "transcription");
$("comment").val(mycomment)

.text() 不输出任何内容。提前感谢您对正确方向的任何提示!

【问题讨论】:

  • 当你 console.log(mycomment) 在你的成功回调中,你得到什么了吗?
  • 不,完全空白
  • PS:如果我用文本替换 xml 注释,我会得到它的输出。但我想要评论:)!

标签: javascript jquery html ajax xml


【解决方案1】:

您的 HTML 元素是 &lt;textarea&gt;,而不是 &lt;comment&gt;,因此 $('comment').val 将不起作用。另外,要获取评论的文本,您应该使用

$(xml).find('ab').text()

only - 使用.attr 设置或获取节点的属性,您并不关心。所以,试试:

const text = $(xml).find('ab').text();
$("#comment").val(text);

前面的# 表示您要查找具有该id 的元素。 (不带任何符号,表示您要查找具有该标签名称的元素。)

在您的 XML 中,如果您想识别类型为 transcriptionab,您可以使用查询字符串:

ab[type="transcription"]

另一个问题是text(或textContent)不能识别评论节点——但是,如果&lt;ab&gt;的内容只是那个评论,那么你可以使用.html.innerHTML检索它。

另外请注意,没有必要为此包含像 jQuery 这样的大型库 - 您可以在 vanilla Javascript 中轻松实现它:

fetch(<url>)
  .then(res => res.text())
  .then((text) => {
    const doc = new DOMParser().parseFromString(text, 'text/html');
    const text = doc.querySelector('ab').innerHTML;
    document.querySelector('#comment').value = text;
  });

演示:

const responseText = `<div>
<ab type="transcription"><!` + `--This is a comment--></ab>
</div>`;

const doc = new DOMParser().parseFromString(responseText, 'text/html');
const text = doc.querySelector('ab').innerHTML;
document.querySelector('#comment').value = text;
&lt;textarea id="comment"&gt;&lt;/textarea&gt;

要访问评论节点的内容,可以使用childNodes[0]导航到该节点,然后获取其textContent

const responseText = `<div>
<ab type="transcription"><!` + `--This is a comment--></ab>
</div>`;

const doc = new DOMParser().parseFromString(responseText, 'text/html');
const text = doc.querySelector('ab').childNodes[0].textContent;
document.querySelector('#comment').value = text;
&lt;textarea id="comment"&gt;&lt;/textarea&gt;

【讨论】:

  • 谢谢 - 是的,我确实使用了 ab[type="transcription"],我尝试了各种混合和匹配,只是为了看看是否有所作为。正如我在原始问题中所写, .text() 不起作用。它在 元素中输出正确的文本,但忽略 cmets。我想输出评论的文字。
  • 啊,我明白了,看来您需要改用.html.innerHTML,请参阅编辑
  • .html 完成了这项工作,谢谢! :) 几个相关的问题:如何在不经过两个步骤(str.replace 或 str.slice,开始首先然后结束)?
  • 另外,更重要的是 - textarea 实际上是一个所见即所得的编辑器,它呈现斜体、粗体等。有没有办法附加评论,以便它在网页上正确呈现?现在它输出带有 text 的斜体(即带有 lg; 和 gt;)。有什么 jquery/javascript 可以做的吗?
  • 看编辑,当然也可以slice一步到位,str.slice(4, str.length - 3)
猜你喜欢
  • 1970-01-01
  • 2013-05-04
  • 2013-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-08
  • 2013-09-01
  • 1970-01-01
相关资源
最近更新 更多