如何创建一个将HTML文件加载到div中的XMLHttpRequest?

时间:2017-06-10 17:26:17

标签: javascript html ajax request xmlhttprequest

我正在尝试制作一个从外部文件加载HTML的XMLHttpRequest,并将该文件的内容插入div

当我运行该函数时,它会在所有正文中插入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>

--------------------------&GT; CSS &lt; --------------------------

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

--------------------------&GT; JS &lt; --------------------------

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

提前致谢。

1 个答案:

答案 0 :(得分:2)

&#13;
&#13;
<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>
&#13;
&#13;
&#13;