2016-06-11 49 views
1

在我的ajax代碼中,我得到了一個html響應。我怎樣才能將整個頁面替換爲這個html響應?我只找到window.location.href,它只能重新訪問url響應。jQuery - 在整個頁面中加載html響應

我的代碼:

$('#btn').click(function(){ 
    $.ajax({ 
     url: '/someurl', 
     data: {'key': value}, 
     type: 'POST', 
     success: function(html_data) { 
      # how to load this html_data into the whole page? 
     }, 
     error: ... 
    }); 
}); 

回答

1

的jQuery replaceWith應該得到它爲你做;)

$("html").replaceWith(data); 

data從服務器接收html ...

整個代碼會是這個樣子......

$.get("yourdomain.com/fileToLoad.html", function(data) { 
    $("html").replaceWith(data); 
}); 

瞭解更多關於jQuery的信息...

http://jquery.com/

+0

嗨,我只是在問題上添加我的代碼。我寫了$('html')。replateWith(html_data),但得到錯誤:「jquery.js:5894 Uncaught HierarchyRequestError:未能在'Node'上執行'replaceChild':'#document-fragment'類型的節點可能不是插入'#document'類型的節點中。「 – Joe

+0

FIne,我只是使用$('html')。html(html_data)來解決這個問題。謝謝! – Joe

+0

很高興幫助:) – shramee

0

window.document是一個對象,方含整個DOM。

嘗試在控制檯window.document中編寫代碼,您將看到您所在頁面的整體結構。如果你只想要body元素,那麼你可以通過標籤找到它,並替換它裏面的內容。

編輯1:

其實你是對的。我沒有測試它。

但你可以做到這一點:

document.open(); 
document.write(your_html); 
document.close(); 

控制檯進行測試。

+0

嗨,像'window.document = html_data'?但沒有迴應... – Joe