【问题标题】:Invalid XML while AJAX return is validAJAX 返回有效时 XML 无效
【发布时间】:2017-05-16 17:13:12
【问题描述】:

我确实使用 jQuery 表单插件和 ajaxSubmit。但是说到返回值,我得到了这个(前面有两行空白,但它们在这里被截断了)。

<?xml version="1.0" encoding="UTF-8"?>
<elements>
 <success>
  <value>282</value>
 </success>
</elements>

ajaxSubmit 调用有一个 dataType: "xml" 并且返回的标头是正确的,但是 ajax 会因“Invalid XML”错误而停止。我认为这两个空白行是不正确的,但即使是修剪也不会删除它们。顺便说一句,XML 生成看起来像这样:

$output = new XMLWriter();
$output->openMemory();
$output->setIndent(true);
$output->startDocument('1.0', 'UTF-8');
$output->startElement("elements");

if (isset($theID)) {
  $output->startElement("success");
  $output->startElement('value');
  $output->text($theID);
  $output->endElement(); //value
  $output->endElement();
}

$output->endElement(); //elements
$output->endDocument();
$xml = $output->outputMemory(true);
header('Content-type: text/xml; charset=utf-8');
print trim($xml);

有人知道这里可能出了什么问题吗?

编辑: 这是 Javascript,但它做得很好(即使有标题,我一开始也没有显示它):

$('#formNewForm').ajaxSubmit({
        dataType: 'xml',
        beforeSubmit: function () {
          // something
        },
        error: function (jqXHR, textStatus, errorThrown) {
          // something
        },
        success: function (responseXML) {
          // something
        }
      });

【问题讨论】:

  • 你可能想发布你的 JS。
  • XML 确实有效。空行应该无关紧要。请发布构建请求并引发异常的 javascript 代码
  • 您是否从浏览器的开发人员工具中的“网络”选项卡中提取了生成的 XML?如果不是,可能值得仔细检查它是否真的相同
  • xml返回值来自chrome开发者工具>网络>响应
  • 您用来处理返回的 xml 的 javascript 在哪里?

标签: jquery ajax xml ajaxform


【解决方案1】:

我在 cmets 中撒谎,我对您的 javascript 进行了更新。这是我的工作代码:

<form id="formNewForm" action="ajax-test.php" method="post">
    <input type="text" name="name">
    <input name="submit" type="submit">
</form>
<script>
    // bind to the form's submit event
    $('#formNewForm').submit(function() {
        // inside event callbacks 'this' is the DOM element so we first
        // wrap it in a jQuery object and then invoke ajaxSubmit
        $(this).ajaxSubmit({
            dataType: 'xml',
            beforeSubmit: function () {
                // something
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // something
            },
            success: function (responseXML) {
                alert(responseXML);
            }
        });

        // !!! Important !!!
        // always return false to prevent standard browser submit and page navigation
        return false;
    });
</script>

【讨论】:

  • 奇怪的事情,这段代码(和我的)在一台服务器上工作,但在另一台服务器上不工作。也许这不是代码问题,而是服务器问题。当我发现更多时,我会回来。
【解决方案2】:

解决方案非常简单,因为它与脚本或生成的 xml 完全无关。它是由一些包含的 php 文件中使用的 php 结束标签(“?>”)引起的,当它后面有一个换行符时。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 2016-06-01
    • 2015-07-08
    • 1970-01-01
    • 2013-10-31
    • 2013-09-22
    • 1970-01-01
    相关资源
    最近更新 更多