【问题标题】:Loading XHTML fragments over AJAX with jQuery使用 jQuery 通过 AJAX 加载 XHTML 片段
【发布时间】:2010-09-14 10:38:06
【问题描述】:

我正在尝试使用 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>

【问题讨论】:

  • 在 jQuery 中使用 XML 类似于在割完草坪后直接驾驶 Bently。

标签: jquery ajax xhtml


【解决方案1】:

试试这个(我刚刚做了一个快速测试,它似乎有效):

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

基本上, .children() 将获取根节点并用它替换 div 的内容。我猜你不能准确地将带有

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多