没有使用jQuery的$.fn.load等效方法

28
我想在按钮点击时将一些Jade内容加载到特定的div中。我已经找到了如何使用jQuery进行此操作的方法,有几篇文章提到了这个问题,基本上我想做的是:
$('#div').load('/somePage');

然而,我在我的项目中无法使用jQuery。 是否有等效的函数可以在原生JavaScript中使用?


1
“Vanilla JavaScript” 没有任何关于 ajax 的规定。浏览器有旧的 XMLHttpRequest API 和新的支持 fetch() API。 - Pointy
1
你可以在http://youmightnotneedjquery.com/找到类似的东西。 - Jimmy Ko
还可以查看 fetch API。 - gcampbell
3个回答

47

我认为你可以通过以下方式实现:

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

顺便提一下,您也可以使用fetch API完成这个任务。

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

顺便提一下,你可以阅读这篇博客文章了解关于fetch API的一些内容。


1
非常好的开始,但我们缺少指定返回页面子集的部分。我在单独的线程中找到了一些关于这个问题的开端。 - quickshiftin
我发现文档未被定义。 - Normajean
@Normajean,你能否发一篇新的问题,并附上你正在使用的一些代码片段? - Ali BARIN
嘿,谢谢你的回复。我刚刚意识到你把这个放在了客户端的JS文件里,对吧?我一直试图在我的Node.js服务器文件中编写它。现在我已经有一个版本可以工作了。 - Normajean
是的,这段代码是为浏览器设计的。由于服务器端没有可用的DOM,因此这个片段将无法直接工作。 - Ali BARIN
显示剩余2条评论

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:
 * https://dev59.com/KloT5IYBdhLWcg3w0SKZ#38132775
 * 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;

        });
};

你如何在服务器端访问document.getElementById(parentElementId).innerHTML = body中的文档?我得到了“document未定义”的错误信息。 - Normajean

0

你可以这样做,但是有一些需要注意的地方。

const getData = (url) => {
  return new Promise((resolve, reject) => {
    let request = new XMLHttpRequest();
    request.onload = function () {
      if (this.readyState === 4 && this.status === 200) {
        resolve(this.responseText);
      } else {
        reject(this.responseText);
      }
    };
    request.open("get", url, true);
    request.send();
  });
};

getData("Your URL")
  .then((resolve) => {
    console.log(resolve);
  })
  .catch((reject) => {
    console.error(reject);
  });

我想让你注意的是,如果你将URL放到一个页面中,它会将其作为字符串从<html>返回到</html>,我猜没有办法像jQuery中的.load()方法一样只获取其中的一部分。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接