2017-06-10 18 views
1

私はXMLHttpRequestを外部ファイルからHTMLをロードし、ファイルの内容をdivに挿入しようとしています。HTMLファイルをdivにロードするXMLHttpRequestを作成するにはどうすればよいですか?

私はこの関数を実行すると、十分でないすべての本文にHTMLを挿入します。

マイコード:

-------------------------->HTML < -------- ------------------

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <script src="shit.js" charset="utf-8"></script> 
    <link rel="stylesheet" href="index.css"> 
    <title>Test</title> 
</head> 
<body> 
    <button type="button" name="button" onclick="send()">Click me</button> 
    <div class="view" id="view"></div> 
</body> 
</html> 

------------------------ - >CSS < --------------------------

.view { 
    margin-top: 5vh; 
    height: 15vh; 
    width: 80vw; 
    background-color: #c1c1c1; 
} 

-------------------------->JS < ------------------ --------

function send() { 
    var xmlhttp = new XMLHttpRequest(); 

    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == 4) { 
      document.write(xmlhttp.responseText); 
     } 
    } 

    var params = "type=search" + "&content=" + encodeURIComponent(document.getElementById("view").innerHTML); 

    xmlhttp.open("GET", "/include/link1.html", true); 
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xmlhttp.setRequestHeader("Content-length", params.length); 
    xmlhttp.send(params); 
}  

ありがとうございます。

+0

あなたは 'のdocument.getElementById( "ビュー")を試してみましたinnerHTMLの= xmlhttp.responseText;'? –

+0

nop、私はそれを試してみる –

+0

私はちょうどその部分でコードを更新しましたが、以前と同じことをやり続けています –

答えて

2

<html> 
 
<head> 
 
<script> 
 
\t var request; 
 

 
\t function sendInfo() { 
 

 
\t \t var url = "NewFile1.html"; 
 

 
\t \t if (window.XMLHttpRequest) { 
 
\t \t \t request = new XMLHttpRequest(); 
 
\t \t } 
 
\t \t else if (window.ActiveXObject) { 
 
\t \t \t request = new ActiveXObject("Microsoft.XMLHTTP"); 
 
\t \t } 
 

 
\t \t try { 
 
\t \t \t request.onreadystatechange = getInfo; 
 
\t \t \t request.open("GET", url, true); 
 
\t \t \t request.send(); 
 
\t \t } 
 
\t \t catch (e) { 
 
\t \t \t alert("Unable to connect to server"); 
 
\t \t } 
 
\t } 
 

 
\t function getInfo() { 
 
\t \t if (request.readyState == 4) { 
 
\t \t \t var val = request.responseText; 
 
\t \t \t document.getElementById('chiru').innerHTML = val; 
 
\t \t } 
 
\t } 
 
</script> 
 
</head> 
 

 
<body> 
 
<marquee><h1>This is an example of ajax</h1></marquee> 
 

 
<form name="vinform"> 
 
\t <input type="button" value="ShowTable" onClick="sendInfo()"> 
 
</form> 
 

 
<span id="chiru"> </span> 
 
</body> 
 
</html>

+0

いくつかのhtmlコンテンツをnewfile1.htmlに入れてこのコードをチェックしてください –

+0

ありがとうChiru!それはうまくいった! –

関連する問題