使用jQuery通过AJAX加载XHTML片段

时间:2020-03-06 14:57:36  来源:igfitidea点击:

我正在尝试使用jQuery的$ .fn.load函数加载XHTML标记的片段,但是在尝试将新标记添加到DOM时会引发错误。我将其范围缩小为XML声明(<?xml ...?>)-如果我返回不带声明的静态文本,则该视图有效。我不明白为什么这会导致失败,或者怪罪于jQuery,Firefox或者我的代码。

如何使用jQuery将XHTML片段插入DOM?

使用$ .get不起作用-回调接收到一个Document对象,当我尝试将其插入DOM时,出现以下错误:

uncaught exception: Node cannot be inserted at the specified point in the hierarchy (NS_ERROR_DOM_HIERARCHY_REQUEST_ERR)
http://localhost:8000/static/1222832186/pixra/script/jquery-1.2.6.js
Line 257

这是我的代码:

$body = $("#div-to-fill");
$.get ("/testfile.xhtml", undefined, function (data)
{
    console.debug ("data = %o", data); // data = Document
    $body.children ().replaceWith (data); // error
}, 'xml');

样本响应:

<?xml version="1.0" encoding="UTF-8"?>
<div xmlns="http://www.w3.org/1999/xhtml">
  <form action="/gallery/image/edit-description/11529/" method="post">
    <div>content here</div>
  </form>
</div>

解决方案

尝试以下方法(我只是做了一个快速测试,它似乎起作用了):

$body = $("#div-to-fill");
$.get ("/testfile.xhtml", function (data)
{
    $body.html($(data).children());
}, 'xml');

基本上,.children()将为我们提供根节点,并用它替换div的内容。我想我们无法将带有<?xml声明的xml文档完全插入到DOM中...