Domanda

Sto cercando di caricare frammenti del markup XHTML usando la funzione $.fn.load di jQuery, ma genera un errore nel tentativo di aggiungere il nuovo markup nel DOM. L'ho ridotto alla dichiarazione XML (<?xml...?>) - la vista funziona se restituisco testo statico senza la dichiarazione. Non capisco perché ciò provocherebbe un errore o se la colpa risiedesse in jQuery, Firefox o nel mio codice.

Come devo inserire frammenti XHTML nel DOM usando jQuery?


L'uso di $ .get non funziona: il callback riceve un oggetto Document e quando provo a inserirlo nel DOM ricevo il seguente errore:

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

Questo è il mio codice:

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

Una risposta di esempio:

<?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>
È stato utile?

Soluzione

Prova invece (ho appena fatto un test rapido e sembra funzionare):

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

Fondamentalmente, .children () ti procurerà il nodo principale e sostituirà con esso il contenuto del tuo div. Suppongo che non sia possibile inserire esattamente un documento XML con la dichiarazione & Lt;? Xml nel DOM ...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top