【问题标题】:'Junk after document element' error in AJAX requestAJAX 请求中的“文档元素后的垃圾”错误
【发布时间】:2016-06-07 20:07:54
【问题描述】:

我正在尝试将 AJAX 与 jQuery 一起使用,但是当我尝试调用 XML 文件时,我收到一条错误消息,提示“文档元素后出现垃圾”。它指向的行是第 3 行,但我看不出第 3 行有什么问题。

当我在 XML 文件中只有 <life> 标记时,XML AJAX 请求正在工作,但是当我添加其他标记时它开始给我这个错误。

<?xml version="1.0" encoding="UTF-8"?>
<life>this is text</life>
<people> This is people</people>
<h2> this is a paragraph</h2>
<div id="ex1">
    <h2>Example 1</h2>
    <p></p>
    <h4>results:</h4>
    <button id="btn">Click for AJAX</button>
</div>
$(document).ready(function() {
    $("button#btn").click(function() {
        let p = document.createElement('p');
        $('div#ex1').append(p);
        $.ajax({
            url: 'sample.xml',
            success: function(data) {
                $('div#ex1 p:last').append(data.querySelector('h2').innerHTML);
            }
        });
    });
});

【问题讨论】:

  • 您的 xml 文档格式不正确。
  • xml中应该有一个根元素
  • 如上所述,XML 格式不正确。解决这个问题,你的代码就可以工作了:jsfiddle.net/RoryMcCrossan/opstmLrp

标签: javascript jquery ajax xml


【解决方案1】:

您的 XML 中有多个“根”元素... 尝试类似以下的...

<?xml version="1.0" encoding="UTF-8"?>
<content>
<life>this is text</life>
<people> This is people</people>
<h2> this is a paragraph</h2>
</content>

【讨论】:

    猜你喜欢
    • 2011-08-30
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 2013-01-22
    相关资源
    最近更新 更多