2017-02-22 3 views
3

이 질문은 이전에 요청했지만 대부분의 대답은 body 태그 또는 jQuery 만 교체 한 것입니다. 일반 JavaScript를 사용하여 DOCTYPE을 (를) 포함한 전체 페이지 내용을 (으)로 대체하고 싶습니다. 또한 window.location.href 페이지를 리디렉션하고 싶지 않습니다. AJAX와 다른 페이지를로드 한 후전체 페이지 내용 바꾸기 (DOCTYPE 사용)

<!DOCTYPE html> 
<html> 

<head> 
    <title>Test</title> 
</head> 

<body> 
    <p>Testing...</p> 
</body> 

</html> 

:이 간단한 페이지 (index.html을)를 가지고

var page; 
var file = new XMLHttpRequest(); 
file.open('GET', './toload.html'); 
file.onreadystatechange = function() { 
    page = file.responseText; 
} 
file.send(); 

을 나는 인 나의 현재 페이지의 내용을 지우고 toload.html의 내용을 표시 할 :

<!DOCTYPE html> 
<html> 

<head> 
    <title>Loaded</title> 
</head> 

<body> 
    <p>Hello. This page is now loaded!</p> 
</body> 

</html> 

어떻게하면됩니까?

+2

'document.write (page);'가 실행합니다. Ajax 프레임 워크를 사용하지 않는 이유가 있습니까? JQuery를 사용하려면'$ ('html') .html (page); – Edward

+1

[Javascript를 사용하여 전체 페이지 바꾸기]의 가능한 복제본 (http://stackoverflow.com/questions/4292603/replacing) -entire-page-head-using-javascript) –

+0

@AndyRay 해당 페이지를 읽었지만 그 중 어떤 메소드도 DOCTYPE을 대체하지 않는다고 생각합니다. –

답변

0

신경 쓰지 마세요. <html> 태그 안의 콘텐츠를 바꿀 수 있다고 결정했습니다. 내가 사용한 코드는 다음과 같습니다.

var contents = "Sorry : (IMPORT FAILED..."; 
var file = new XMLHttpRequest(); 
file.open("GET", "/toload.html", false); 
file.onreadystatechange = function() { 
    contents = file.responseText; 
} 
file.send(null); 
document.getElementsByTagName("html")[0].innerHTML = contents; 

어쨌든 멋진 답변을 보내 주셔서 감사합니다.

2

내가 얻을 수있는 가장 가까운입니다

document.getElementsByTagName('html')[0].innerHTML=""; 

병이 업데이트를 사용하면 DOM의 루트 노드를 취소 할 수없는 이유를 알아낼 수 있다면이 답변.