如何使XMLHttpRequest将HTML文件加载到div中? [英] How to make an XMLHttpRequest that loads an HTML file into the div?

查看:121
本文介绍了如何使XMLHttpRequest将HTML文件加载到div中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

当我运行该函数时,它会在所有正文中插入HTML,这是不够的.

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

我的代码:

--------------------------> 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 < ---------- ----------------

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

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

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

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

谢谢.

推荐答案

<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>

这篇关于如何使XMLHttpRequest将HTML文件加载到div中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆