Loading XHTML fragments over AJAX with jQuery

放肆的年华 提交于 2019-12-21 09:07:24

问题


I'm trying to load fragments of XHTML markup using jQuery's $.fn.load function, but it raises an error trying to add the new markup into the DOM. I've narrowed this down to the XML declaration (<?xml...?>) -- the view works if I return static text without the declaration. I don't understand why this would cause failure, or if the blame lies in jQuery, Firefox, or my code.

How should I insert XHTML fragments into the DOM using jQuery?


Using $.get does not work -- the callback receives a Document object, and when I try to insert it into the DOM, I receive the following error:

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

This is my code:

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

A sample response:

<?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>

回答1:


Try this instead (I just did a quick test and it seems to work):

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

Basically, .children() will get you the root node and replace the content of your div with it. I guess you can't exactly insert an xml document with the <?xml declaration into the DOM...



来源:https://stackoverflow.com/questions/156133/loading-xhtml-fragments-over-ajax-with-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!