tags:

views:

3949

answers:

2

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"&gt;
  <form action="/gallery/image/edit-description/11529/" method="post">
    <div>content here</div>
  </form>
</div>
A: 

You should try a different jQuery function (such as .get) which supports a 'type' parameter and specify 'xml'.

Something like this (this will print the xml reponse from test.php):

jQuery.get("test.php", null, function(response){
  alert(response);
},"xml");

Edit: Just noticed you said XHTML response and not XML response. Unless the response litterally is XML, you should not be returning another (assuming you have one above the header) xml declaration. If the response is just XHTML that you want inserted into the DOM, add some conditionals to only return exactly what you need - or return JSON and insert into the DOM via jQuery.

leek
Updated the question to contain results of $.get. The response is a valid XML document, being inserted into an XHTML document.
John Millikin
+6  A: 

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

Ricky
Just tested this, and it almost worked -- for some reason, the fragment is being inserted twice.
John Millikin
oh crap! let me take a look again
Ricky
Never mind, solved that problem (was unrelated). Thank you very much for the working solution.
John Millikin
hmm, what if you do this instead: .html($(data).children()[0]);BTW, for me it is inserting it correctly - only once...
Ricky