相当于没有jQuery的$ .load

Woo*_*der 10 javascript jquery node.js express pug

我想在点击按钮时将一些Jade内容加载到某个div中.我已经找到了如何用jquery做这个,有几个帖子,基本上我想做的是

$('#div').load('/somePage');
Run Code Online (Sandbox Code Playgroud)

但是,我无法在我的项目中使用jQuery.在vanilla javascript中是否有相同的功能?

Ali*_*RIN 18

我想你可以用以下方法做到这一点;

var request = new XMLHttpRequest();

request.open('GET', '/somepage', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    var resp = request.responseText;

    document.querySelector('#div').innerHTML = resp;
  }
};

request.send();
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您也可以使用fetch API执行此操作.

fetch('/somepage')
  .then(function(response) {
    return response.text();
  })
  .then(function(body) {
    document.querySelector('#div').innerHTML = body;
  });
Run Code Online (Sandbox Code Playgroud)

顺便说一下,您可以阅读此博客文章,了解有关fetch API的信息.


Phr*_*cis 6

当我试图解决同样的问题时,我根据Ali BARIN 的回答做了这个,看起来效果很好,但它是一个更明确的版本,添加了init信息,并且有一些逻辑可以用来document.getElementById代替querySelector.

/*
 * Replicates the functionality of jQuery's `load` function, 
 * used to load some HTML from another file into the current one.
 * 
 * Based on this Stack Overflow answer:
 * /sf/answers/2669294281/
 * And `fetch` documentation:
 * https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
 * 
 * @param {string} parentElementId - The ID of the DOM element to load into
 * @param {string} htmlFilePath - The path of the HTML file to load
 */
const loadHtml = function(parentElementId, filePath) {
    const init = {
        method : "GET",
        headers : { "Content-Type" : "text/html" },
        mode : "cors",
        cache : "default"
    };
    const req = new Request(filePath, init);
    fetch(req)
        .then(function(response) {
            return response.text();
        })
        .then(function(body) {
            // Replace `#` char in case the function gets called `querySelector` or jQuery style
            if (parentElementId.startsWith("#")) {
                parentElementId.replace("#", "");
            }
            document.getElementById(parentElementId).innerHTML = body;

        });
};
Run Code Online (Sandbox Code Playgroud)