14

我正在开发一个脚本,但我不能使用 jQuery 库,所以我需要 JS 中的 .load() 等价物。

我需要在没有 jQuery 的情况下执行此操作:

$(document).ready(function(){

$('#a').click(function(){
   $('body').append('<div id="b"></div>')
   $('#b').load('x.html')
});

});

谢谢!

4

7 回答 7

13

更新:

将 Fetch API 与 .then() 一起使用

function load(url, element)
{
    fetch(url).then(res => {
        element.innerHTML = res; 
    });
}

旧的 XMLHttpRequest

function load(url, element)
{
    req = new XMLHttpRequest();
    req.open("GET", url, false);
    req.send(null);
    
    element.innerHTML = req.responseText; 
}

用法

load("x.html", document.getElementById("b"));
于 2013-07-27T18:42:16.910 回答
7

简单的答案是,如果没有像 jQuery 这样的库,您正在做的事情要正确完成相当复杂。这是“有效”的东西,但没有错误检查或跨浏览器完美。你真的可能不想要这个......但它就在这里。

<!DOCTYPE html>
<html>
<head>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            document.getElementById('a').addEventListener('click', function (e) {
                e.preventDefault();

                var div = document.createElement('div');
                div.id = 'b';
                document.body.appendChild(div);

                var xhr = new XMLHttpRequest();

                xhr.onload = function () {
                    div.innerHTML = this.response;
                };

                xhr.open('GET', 'x.html', true);
                xhr.send();
            }, false);
        }, false);
    </script>
</head>
<body>
    <a id="a" href="#">load</a>
</body>
</html>
于 2013-07-27T18:47:17.597 回答
3

如果您想在没有 JS 的情况下执行此操作,我认为这会对您有所帮助,请在里面添加#b

<iframe src="x.html"></iframe> 
于 2013-07-27T18:40:14.657 回答
2

更新:

将 Fetch API 与 .then() 一起使用

function load(url, element)
{
    fetch(url).then(res => {
        element.innerHTML = res; 
    });
}

旧的 XMLHttpRequest

function load(url, element)
{
    req = new XMLHttpRequest();
    req.open("GET", url, false);
    req.send(null);
    
    element.innerHTML = req.responseText; 
}

用法

load("x.html", document.getElementById("b"));

这将加载“x.html”并将其放入元素中。

于 2018-06-28T14:09:28.760 回答
0
var xmlhttp;
if (window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
} else {
    xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}

/* If you wanted post too */    
// xmlhttp.open("POST", "/posturl", true);
// xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// xmlhttp.send("email=" + "value" + "&message=" + "value" + "&name=" + name"value");

xmlhttp.open("GET", "file_to_get.xml", true/* async, setting to false will block other scripts */);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        window.alert(xmlhttp.responseText);
    }
}
于 2013-07-27T19:01:01.297 回答
0
<object type="text/html" data="my.html">
于 2013-07-27T18:41:51.220 回答
0

我发现 jquery 从加载的文件中加载运行脚本,将 innerHTML 设置为某些东西并不能解决问题......不要测试你是否可以在之后调用 init() 函数......

于 2019-02-18T22:02:32.363 回答