小编典典

如何使XMLHttpRequest将HTML文件加载到div中?

ajax

我正在尝试XMLHttpRequest从外部文件加载HTML并将文件的内容插入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>

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

提前致谢。


阅读 284

收藏
2020-07-26

共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>
2020-07-26