How to make an XMLHttpRequest that loads an HTML file into the div?

£可爱£侵袭症+ 提交于 2020-05-08 18:57:30

问题


I'm trying to make an XMLHttpRequest that loads HTML from an external file and inserts the content of the file into the div.

When I run the function, it inserts the HTML in all of the body which is not adequate.

My code:

--------------------------> 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);
}    

Thanks in advance.


回答1:


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

	function sendInfo() {

		var url = "NewFile1.html";

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

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

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

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

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

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


来源:https://stackoverflow.com/questions/44476100/how-to-make-an-xmlhttprequest-that-loads-an-html-file-into-the-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!