2008-10-01 55 views
9

我試圖加載使用jQuery的$.fn.load功能XHTML標記的片段,但它提出了嘗試新的標記添加到DOM發生錯誤。我已經縮小到XML聲明(<?xml...?>) - 如果我沒有聲明返回靜態文本,視圖就可以工作。我不明白爲什麼這會導致失敗,或者如果責備在於jQuery,Firefox或我的代碼。加載XHTML片段在AJAX使用jQuery

我應該如何插入XHTML片段到使用jQuery的DOM?


使用$不用彷徨不工作 - 回調接收一個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> 

回答

15

試試這個(我只是做了一個快速測試,它似乎工作):

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

基本上,。孩子()將讓你的根節點來覆蓋你的div的內容。我想你可以不完全插入與<?xml聲明的XML文檔到DOM ...